合并2数组保留旧值并使用新值扩展,如果需要也可以扩展

时间:2018-05-20 22:43:28

标签: javascript angular typescript ionic-framework

我有这个对象

array1=[0:{
 title:"title",
  notes:[
   0:{body:"text"}
   1:{body:"text"}
   2:{body:"some other text"}
  ]
}]

array2=[0:{
 title:"title",
  notes:[
   0:{body:"text"}
   1:{body:"text sfhhda"}
  ]
}]

我需要合并以获得像这样的输出

的console.log(合并(数组1,数组2)) =>

[0:
 {title:"title",
  notes:[
   0:{body:"text"}
   1:{body:"text text sfhhda"}
   2:{body:"some other text"}
  ]
}]

是否有任何方法可以做到这一点?

1 个答案:

答案 0 :(得分:0)

您可以组合数组并使用键值字符串编制索引,并获取Map的值:



const array1=[{title:"title",notes:[{body:"text"},{body:"text"},{body:"some other text"}]}]
const array2=[{title:"title",notes:[{body:"text"},{body:"text sfhhda"}]}]

const notesMap = [...array1[0].notes, ...array2[0].notes]
  .reduce((a, obj) => (
    a.set(JSON.stringify(obj), obj)
  ), new Map());

const output = [{
  title: 'title',
  notes: [...notesMap.values()]
}];
console.log(output);