Reputation: 107
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
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
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