我的Json看起来像
[{"name":"a","value":1},
{"name":"b","value":2},
{"name":"c","value":3},
{"name":"d","value":4}]
通过
获取这些Json数据到我的项目中
this.http.get('http://localhost:8000/names')
.map(response=>response.json())
.subscribe(data=>{this.names = data});
中添加一个新对象
"name":"new","value":5
我试过这样:
for(i in this.alldepartment){}
// alert(i) -> it alerts 3
this.names[++i]["name"]="new";
this.names[++i]["value"]=5;
alert(JSON.stringify(this.names));
但它不起作用。我想成为
[{"name":"a","value":1},
{"name":"b","value":2},
{"name":"c","value":3},
{"name":"d","value":4},
{"name":"new","value":5}]
有没有解决方案?
答案 0 :(得分:1)
解决方案1 :
data.push({name: "e", value: 5});
解决方案2(ES6):
this.names = [ ...data, { name: "e", value: 5}];
答案 1 :(得分:0)
您可以使用Array的push()函数。 push()方法将一个或多个元素添加到数组的末尾,并返回数组的新长度。
this.names = [];
//or in your case
this.names = [{ "name": "a", "value": 1 },
{ "name": "b", "value": 2 },
{ "name": "c", "value": 3 },
{ "name": "d", "value": 4 }];
this.http.get('http://localhost:8000/names')
.map(response => response.json())
.subscribe(data => {
//data => { "name": "e", "value": 5}
this.names.push(data);
},
err=>{
console.log(err);
},
()=>{
alert(JSON.stringify(this.names));
}
);
希望有所帮助。您可以在以下位置阅读有关此功能的更多信息 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push?v=a