如何在JavaScript中使用变量的值扩展JSON对象?

时间:2018-11-27 18:04:30

标签: javascript json

如何在JavaScript中使用变量的值扩展JSON对象? 这是我的代码。

addIndexedResult = (inid) => { 
let url = 'https://jsonplaceholder.typicode.com/todos/'+inid
fetch(url)
  .then(response => response.json())
  .then(json => {
      console.log(json);
      // augment json with id & sort it out later in the browser
      let jsonAug = {inid: {...json}}; //output: {"inid":{"userId":1,"id":7,"title":"illo expedita consequatur quia in","completed":false}}
      let my_results = this.state.myResults; 
      my_results.push(jsonAug);
      this.setState(prevState => ({
        myResults: my_results
      }));          
  })
}

通知let jsonAug = ...语句的输出不评估变量inid

如何使用inid扩展json?

2 个答案:

答案 0 :(得分:0)

您应该将获取的id返回的json值直接分配给id中的jsonAug值,如下所示:

let jsonAug = {id: json.id};

完整的示例可能像这样

addIndexedResult = (id) => { 
    let url = 'https://jsonplaceholder.typicode.com/todos/'+id
    fetch(url)
    .then(response => response.json())
    .then(json => {
        console.log(json);
        // augment json with id & sort it out later in the browser
        let jsonAug = {id: json.id}; //output: {"id":{"userId":1,"id":7,"title":"illo expedita consequatur quia in","completed":false}}
        let my_results = this.state.myResults; 
        my_results.push(jsonAug);
        this.setState(prevState => ({
          myResults: my_results
        }));          
    })
}

答案 1 :(得分:0)

使用Objet.assign

~/.config/gcloud