如何使用 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?
您应该将从 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
}));
})
}