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

问题描述 投票:0回答:2

如何使用 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

value
来扩充 json?

javascript json
2个回答
0
投票

您应该将从 fetch 的

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
        }));          
    })
}

0
投票

您可以使用计算属性名称(ES6功能)

例如

let inid: string = "myKey";

let jsonAug = {[inid]: {...json}};
//              ^^^^  - Computed Property Name
//             ^    ^ - NOTE: the square brackets around the `key`!!

或者,您可以使用括号表示法

例如

let inid: string = "myKey";

let jsonAug = {};
jsonAug[inid] = {... json} // shallow-copy
© www.soinside.com 2019 - 2024. All rights reserved.