简体   繁体   English

TypeScript迭代JSON并放入JSON元素

[英]TypeScript Iterate JSON and put JSON elements

I'm new to TypeScript but what I want to do is fairly simple but the documentation doesn't seem to cover iteration over JSON. 我是TypeScript的新手,但是我想做的事情很简单,但是文档似乎并未涵盖JSON的迭代。 What I want to do is iterate over a JSON response array and put a JSON object into each JSON element. 我想做的是遍历JSON响应数组,并将JSON对象放入每个JSON元素中。 Here's the code I'm working with, the TypeScript evaluator in WebStorm is telling me that speakerElement is a string and not JSON so I can't use the put function. 这是我正在使用的代码,WebStorm中的TypeScript评估程序告诉我speakerElement是字符串而不是JSON,所以我不能使用put函数。

return new Promise(resolve => {
   this.http.get('http://.staging.wpengine.com/wp-json/wp/v2/cr3ativspeaker')
   .map(res => res.json())
.subscribe(data => {
  console.log("the speaker data is : ", data);
  console.log("the speaker data is : ", JSON.stringify(data));
  //get each speakers image and append it to their data
  for(let speakerElement in <JSON>data) {

    this.http.get('http://.staging.wpengine.com/wp-json/wp/v2/cr3ativspeaker')
      .map(res => res.json())
      .subscribe(response => {

       speakerElement.put("media_details", response.media_details);

      });

  }

  this.data = data;
  resolve(this.data);
});
});

Firstly, Everyone thanks for the suggestion. 首先,大家感谢这个建议。 I found the answer which required a very small change. 我发现答案需要很小的改变。 I was using in in my For Loop . 我用in我的For Loop I needed to use of . 我需要使用of The correct code is 正确的代码是

 for(let speakerElement of data) {
            console.log("Speaker element",speakerElement);// element is JSON 

          }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM