todd
todd

Reputation: 335

Javascript add item in Object

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

Answers (6)

Mohammad Usman
Mohammad Usman

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

Prasanna Brabourame
Prasanna Brabourame

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

Rakibul Hasan
Rakibul Hasan

Reputation: 490

try this

var arr = [{
          id: '1',
          total: "Total:",
          titlea: 'a',
          titleb: 'b',
       }];

    arr[0]["titlec"] = "c";
    console.log(arr)

Upvotes: 0

user7896971
user7896971

Reputation:

let key = Object.keys(c)[0];
let value = c.titlec;
arr[0][key] = value;

Upvotes: 1

flyingfox
flyingfox

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

brk
brk

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

Related Questions