0

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?

0

2 Answers 2

3

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)

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

Comments

3

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

1 Comment

Don't understand the downvote. this is a valid answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.