我觉得我有一个很简单的问题,但我只是没有得到答案......
我使用 JSON.parse 将服务器响应的 .text() 解析为 JSON。
我实际上可以通过以下方式访问该 JSON 的值:this.temp[0].name
。
现在我只想遍历该 JSON 并将值推送到字符串数组中。但我怎样才能做到这一点?
当我尝试使用 for...of
时,编译器需要一个字符串或数组而不是 JSON。当我尝试使用 for...in
时,它实际上并没有进入循环。
这是一些我可以正常访问的代码:
this._pS.getAllProjects()
.subscribe(data => this.temp = JSON.parse(data.text()),
err => console.log(err),
() => console.log("hello " + this.temp[0].name + this.temp[1].name));
当我在 .stringify() 之后打印出来时:
this._pS.getAllProjects()
.subscribe(data => this.temp = JSON.stringify(data),
err => console.log(err),
() => console.log("hello " + this.temp));
我在浏览器控制台中得到这个:
{"_body":"[{\"name\":\"Projekt A\"},{\"name\":\"Projekt XYZ\"}]",
"status":200,
"ok":true,
"statusText":"Ok",
"headers":{"Content-Type":["application/json; charset=utf-8"]},
"type":2,
"url":"http://127.0.0.1:3000/api/getAllProjectNames"}
tl;dr:如何将正文文本部分的值放入字符串数组?
提前致谢
最佳答案
如果响应是您包含的内容,那么很简单:
JSON.parse(data.text()).forEach(item => {
console.log(item.name);
});
因为你的 body 是这个接口(interface)的对象数组:
interface ObjectInResponseArray {
name: string;
}
关于javascript - 将JSON转换为 typescript 中的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37219724/