-1

I have code to merge two objects

Here is code

var obj1 = [{ food: 'pizza', car: 'ford'},
{food:'apple',car:'volvo'}];
var obj2 = { animal: 'dog' }


var allRules = Object.assign({}, obj1, obj2);

console.log(allRules);

It works, but in new object I have two elements and dog as 3 element. You can see it from snippet.

But I need two elements with dog as property. So it will be food, car and animal as key in every element of object.

How I can do this?

UPDATE

For merging array with object property I understood, but if I have two arrays like this

    var arr1 = [{
    food: 'pizza',
    car: 'ford'
  },
  {
    food: 'apple',
    car: 'volvo'
  }
];

var arr2 = [{
  animal: 'dog'
},
{animal:'cat'}
];

And want to merge it to one array with 1 element of 1 array, get's 1 element of 2 array , etc.

How I can do this?

Yevhen
  • 1
  • 5

3 Answers3

1

obj1 is an array, so you need to iterate this array and assign the obj2 to each item in the array.

Use map

var allRules = obj1.map( s => Object.assign({}, s, obj2) );

Demo

var obj1 = [{ food: 'pizza', car: 'ford'},
{food:'apple',car:'volvo'}];
var obj2 = { animal: 'dog' }


var allRules = obj1.map( s => Object.assign({}, s, obj2) );

console.log(allRules);

Edit

For the updated question

var allRules = obj1.map( (s,i) => Object.assign({}, s, obj2[i]) );
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

You need to iterate the array and then assign Object.assign() on item's of the array.

var obj1 = [{
    food: 'pizza',
    car: 'ford'
  },
  {
    food: 'apple',
    car: 'volvo'
  }
];

var obj2 = {
  animal: 'dog'
}

obj1.forEach(x => Object.assign(x, obj2));
console.log(obj1);

As per comment

var arr1 = [{
    food: 'pizza',
    car: 'ford'
  },
  {
    food: 'apple',
    car: 'volvo'
  }
];

var arr2 = [{
    animal: 'dog'
  },
  {
    animal: 'cat'
  }];

arr1.forEach((item, index) => Object.assign(item, arr2[index]));
console.log(arr1);
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

Your first object is actually an array. You can map over it and assign your object into object into array. See this snippet:

var myArray = [{ food: 'pizza', car: 'ford'},
               { food: 'apple', car: 'volvo'}];
var obj = { animal: 'dog' };
var newArray = myArray.map((o) => Object.assign({}, o, obj));

console.log(newArray);

I changed variable names to myArray and newArray for you to see what you're dealing with.

Tomasz Bubała
  • 2,093
  • 1
  • 11
  • 18