Reputation: 335
this is my code
var arr = [{
id: '1',
total: "Total:",
titlea: 'a',
titleb: 'b',
}];
let c= {titlec: 'c'}
arr.push(c);
console.log(arr)
So the console.log shows that
0: {id: "1", totalPdf: "Total:", titlea: "a", titleb: "b"}
1: {titlec: "c"}
But I want it as:
0: {id: "1", totalPdf: "Total:", titlea: "a", titleb: "b", titlec: "c"}
How can I do that? Thanks
Upvotes: 1
Views: 987
Reputation: 39332
Iterate over your data set using .forEach()
or .map()
and use Object.assign()
to add properties of the c
object to objects in array.
let arr = [{
id: '1',
total: "Total:",
titlea: 'a',
titleb: 'b',
}];
let c = {titlec: 'c'}
arr.forEach(o => Object.assign(o, c));
console.log(arr);
Upvotes: 3
Reputation: 847
If the condition is needed for only single use you can use by using the below simple code it will work correctly without using any loop statement.
arr[0]['titlec'] = c.titlec
Upvotes: 0
Reputation: 490
try this
var arr = [{
id: '1',
total: "Total:",
titlea: 'a',
titleb: 'b',
}];
arr[0]["titlec"] = "c";
console.log(arr)
Upvotes: 0
Reputation:
let key = Object.keys(c)[0];
let value = c.titlec;
arr[0][key] = value;
Upvotes: 1
Reputation: 13506
push()
will add a new element to the array,you should not use it
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)
Upvotes: 0
Reputation: 50316
arr.push(c);
will push a new element to the object.Instead use array map
& Object.assign
.Array map
will return a new array and with updated object value
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)
Upvotes: 0