最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Map object array inside another object array - Stack Overflow

programmeradmin1浏览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?

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?

Share asked May 23, 2017 at 10:08 EvgenyEvgeny 1074 silver badges17 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 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)

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;
});
发布评论

评论列表(0)

  1. 暂无评论