如何在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?
答案 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