Object.assign()和对象数组

时间:2018-11-20 09:01:39

标签: javascript arrays spread-syntax

我有一个像这样的嵌套数组

const names= [[{name: "John"}, {name: "Mary"}],
           [{name: "Paul"}, {name: "Peter"}]];

我想将country注入嵌套对象

const country = {country :"USA"}

所以输出看起来像

[{name: "John", country : "USA"}, {etc} ,{etc} ]

代码构想就是这样

const combined = names.map((map)=> 
       Object.assign({}, 
              country, 
              /*something to extract name from nested array names*/),
       {country}
         )

有人建议我如何将对象分布在嵌套数组中以形成所需的输出吗?

如果可以通过其他方式改进代码,请也告诉我

6 个答案:

答案 0 :(得分:3)

在使用flat()之前,您可以使用map()创建一个包含所有子数组元素的新数组,如下所示:

const names= [[{name: "John"}, {name: "Mary"}],
           [{name: "Paul"}, {name: "Peter"}]];
const country = {country :"USA"}
const combined = names.flat().map(p => Object.assign(p, country));
console.log(combined);

答案 1 :(得分:3)

利用reduce来使数组以及map和object.assign变平,以将国家/地区值添加到每个对象

const names= [[{name: "John"}, {name: "Mary"}],
           [{name: "Paul"}, {name: "Peter"}]];
const country = {country :"USA"};
const newNames = names.reduce((acc, item) =>{
    acc= acc.concat(item.map(value => Object.assign({}, value, country)));
    return acc;
},[]);
console.log(newNames);

答案 2 :(得分:1)

这是关于在外部map中使用嵌套的map

const names = [
  [{
    name: "John"
  }, {
    name: "Mary"
  }],
  [{
    name: "Paul"
  }, {
    name: "Peter"
  }]
]

const country = { country: 'USA' }

const output = names.map (xs => xs.map (x => ({ ...x, ...country })))

console.log (output)

答案 3 :(得分:0)

您可以声明一个新的数组文字,将country列为第一项,然后将names[0]数组扩展到其中,无需使用Object.assign.map,如果您只有一个子数组:

const names= [[{name: "John"}, {name: "Mary"}],
           [{name: "Paul"}, {name: "Peter"}]];
const country = {country :"USA"};
const newNames = [[country, ...names[0]]];
console.log(newNames);

答案 4 :(得分:0)

您可以将名称数组及其嵌套数组进行双重映射,并在每个项目中分解国家/地区。

const names = [[{name: "John"}, {name: "Mary"}],
           [{name: "Paul"}, {name: "Peter"}]];
           
const country = {country :"USA"};

const namesWithCountry = names.map(name => name.map(n => ({...n, ...country})));

console.log(namesWithCountry);

答案 5 :(得分:0)

您可以在外部映射中使用另一个public static <T> T initializeAndUnproxy(T entity) { if (entity == null) { throw new NullPointerException("Entity passed for initialization is null"); } Hibernate.initialize(entity); if (entity instanceof HibernateProxy) { entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer() .getImplementation(); } return entity; } 来遍历对象的每个内部数组:

map