这是我的代码
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"}
我该怎么做?谢谢
答案 0 :(得分:3)
使用.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);
答案 1 :(得分:1)
arr.push(c);
会将新元素推送到对象。请使用数组map
和Object.assign
。数组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)
答案 2 :(得分:1)
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)
答案 3 :(得分:1)
let key = Object.keys(c)[0];
let value = c.titlec;
arr[0][key] = value;
答案 4 :(得分:1)
尝试
var arr = [{
id: '1',
total: "Total:",
titlea: 'a',
titleb: 'b',
}];
arr[0]["titlec"] = "c";
console.log(arr)
答案 5 :(得分:0)
如果该条件仅需单次使用,则可以使用以下简单代码使用,它将在不使用任何循环语句的情况下正常运行。
arr[0]['titlec'] = c.titlec