【发布时间】:2016-09-10 05:23:20
【问题描述】:
我觉得我有一个很简单的问题,但我就是没有得到答案......
我使用 JSON.parse 将来自服务器的响应的 .text() 解析为 JSON。
我实际上可以通过this.temp[0].name 访问该 JSON 的值。
现在我只想遍历那个 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:如何将正文文本部分的值放入字符串数组中?
提前致谢
【问题讨论】:
标签: javascript arrays json typescript angular