1

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

3
  • Look up how to assign properties to objects. Commented Oct 7, 2018 at 6:27
  • arr[0].titlec="c" or its equal arr[0]["titlec"]="c" Commented Oct 7, 2018 at 6:29
  • Do you want 0: {id: "1", totalPdf: "Total:", titlea: "a", titleb: "b", titlec: "c"} or {id: "1", totalPdf: "Total:", titlea: "a", titleb: "b", titlec: "c"}? Commented Oct 7, 2018 at 8:20

6 Answers 6

3

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);

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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)

Comments

0

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)

2 Comments

Why the loop? .
@mplungjan My answer is suppose object c has many properties
0

try this

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

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

3 Comments

This seems to be hard coding
this is not a generic solution.
I already tried this, but i don't think this is a good way, but thank you
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.