我有下面的代码使用它能够将新行推入我的json对象,但是无法将父字段名像(d0,d1,d2 ..)添加到新添加的行中,我该怎么办?< / p>
代码:
var d = [{
"id": 0,
"name": "Housing",
"value": 71
}, {
"id": 1,
"name": "Travel",
"value": 85
}, {
"id": 2,
"name": "Restaurant",
"value": 44
}, {
"id": 3,
"name": "Bank",
"value": 33
}];
var dataset = {};
d.forEach(function (e, i) {
dataset['d' + i] = e;
});
alert(JSON.stringify(dataset,null,2));
var input='Banking';
var dataset_final={};
d.forEach(function (e, i) {
counter=i;
});
alert(counter+1);
var input='Movies';
d.push({id:counter+1,name:input,value:"3"});
alert(JSON.stringify(d,null,2))
我想直接将数据推送到'dataset'变量。如何为第4行添加像'd4'这样的父字段名称,这些名称将为名称添加:电影?
答案 0 :(得分:3)
您可以这样做:
var counter = Object.keys(dataset).length;
dataset['d' + counter] = {name: 'Banking', value: 100};