Evgeny
Evgeny

Reputation: 107

Map object array inside another object array

I've got two arrays, one of which I want to map with another one as an object. For example :

var myArray = [{'id' : 'first', 'name' : 'firstname'}];
var addressArray = [{'city' : 'London', 'street' : 'Oxford'}];

I want to put adress array inside myArray as an object so that I have :

var newArray = [{'id' : 'first', 'name' : 'firstname', 'address' : {'city' : 'London', 'street' : 'Oxford'}}];

I have tried mapping with forEach method :

myArray.forEach(function(o, i){
    o.address = addressArray;
});

But I keep getting [Object] in my output :

[{'id' : 'first', 
  'name' : 'firstname', 
  'address' : [[Object], [Object]] }]

What is the best way to do it?

Upvotes: 0

Views: 5022

Answers (2)

FrankCamara
FrankCamara

Reputation: 348

Use map instead since it is actually a new array you are returning with modyfied items in it

var res = myArray.map((item, index) => {
  item.address = addressArray[index];
  return item;
});

Upvotes: 3

Satpal
Satpal

Reputation: 133453

Use index to access the element

myArray.forEach(function(o, i){
    o.address = addressArray[i];
});

var myArray = [{'id' : 'first', 'name' : 'firstname'}];
var addressArray = [{'city' : 'London', 'street' : 'Oxford'}];

myArray.forEach(function(o, i){
    o.address = addressArray[i];
});

console.log(myArray)

Upvotes: 3

Related Questions