这是我的代码
var arr = [{
id: '1',
total: "Total:",
titlea: 'a',
titleb: 'b',
}];
let c= {titlec: 'c'}
arr.push(c);
console.log(arr)
所以console.log显示了这一点
0: {id: "1", totalPdf: "Total:", titlea: "a", titleb: "b"}
1: {titlec: "c"}
但我想要它:
0: {id: "1", totalPdf: "Total:", titlea: "a", titleb: "b", titlec: "c"}
我怎样才能做到这一点?谢谢
使用.forEach()
或.map()
迭代数据集,并使用Object.assign()
将c
对象的属性添加到数组中的对象。
let arr = [{
id: '1',
total: "Total:",
titlea: 'a',
titleb: 'b',
}];
let c = {titlec: 'c'}
arr.forEach(o => Object.assign(o, c));
console.log(arr);
arr.push(c);
将一个新的元素推送到object.Instead使用数组map
和Object.assign
.Array map
将返回一个新的数组并具有更新的对象值
var arr = [{
id: '1',
total: "Total:",
titlea: 'a',
titleb: 'b',
}];
let c = {
titlec: 'c'
}
let m = arr.map(function(item) {
return Object.assign(item, c)
})
console.log(m)
push()
将为数组添加一个新元素,你不应该使用它
var arr = [{
id: '1',
total: "Total:",
titlea: 'a',
titleb: 'b',
}];
let c= {titlec: 'c'}
for(var i in c){
arr[0][i]=c[i];
}
console.log(arr)
let key = Object.keys(c)[0];
let value = c.titlec;
arr[0][key] = value;
试试这个
var arr = [{
id: '1',
total: "Total:",
titlea: 'a',
titleb: 'b',
}];
arr[0]["titlec"] = "c";
console.log(arr)
如果只需要一次性使用该条件,您可以使用下面的简单代码,它可以正常工作,而无需使用任何循环语句。 arr[0]['titlec'] = c.titlec