我试图在JavaScript数组中的每个对象中添加一个新字段(sid):
dataset_sk_final = [
{'id':0,'name':'Banking'},
{'id':1,'name':'Home'},
{'id':2,'name':'Travel'}
]
我的输出应该是 -
dataset_sk_final = [
{'id':0,'name':'Banking','sid':''},
{'id':1,'name':'Home','sid':''},
{'id':2,'name':'Travel','sid':''}
]
我尝试使用下面的代码,但它不起作用,我缺少什么?
var dataset_sk_final1 = [];
object.keys(dataset_sk_final).foreach(function (key) {
'sid' = ''
}
dataset_sk_final1.push(dataset_sk_final[key]);
alert('after assigning final:'+json.stringify(dataset_sk_final1),null,2);
答案 0 :(得分:1)
首先在Array
对象中没有方法foreach
,但有forEach
(case sensitive
),第二个 - 将新属性分配给Object
你可以el.sid = ''
使用el['sid'] = ''
或dot notation 'sid'=''
而不是String
,因为它只是var dataset_sk_final = [
{'id':0,'name':'Banking'},
{'id':1,'name':'Home'},
{'id':2,'name':'Travel'}
];
dataset_sk_final.forEach(function (el) {
el.sid = '';
});
console.log(JSON.stringify(dataset_sk_final, null, 2));
{{1}}
答案 1 :(得分:0)
这应该有用吗?
for(var index in data_sk_final) {
data_sk_final[index].sid = ''
}
所以你的例子变成了
dataset_sk_final = [
{'id':0,'name':'Banking'},
{'id':1,'name':'Home'},
{'id':2,'name':'Travel'}
]
for(var index in data_sk_final) {
data_sk_final[index].sid = ''
}
alert('after assigning final:'+json.stringify(dataset_sk_final),null,2);