Javascript数组对象复制合并

问题描述 投票:0回答:1

There are now two arrays

第一个数组:

var arr = [
   {path: '/a', name: 'aa'},
   {path: '/f', name: 'ff'}
];

两个阵列:

var arr1 = [
   {path: '/a', meta: {title:'aa2', hidden: 1}},
   {path: '/b', meta: {title:'bb', hidden: 1}},
   {path: '/c', meta: {title:'cc', hidden: 0}},
   {path: '', meta: {title:'dd', hidden: 0}}
   {path: '', meta: {title:'ee', hidden: 0}}
 ]

我想将它们合并到这个:

var arr2 = [
  {path: '/a', name: 'aa', meta: {title:'aa2', hidden: 1}},
  {path: '/b', meta: {title:'bb', hidden: 1}},
  {path: '/c', meta: {title:'cc', hidden: 0}},
  {path: '', meta: {title:'dd', hidden: 0}},
  {path: '', meta: {title:'ee', hidden: 0}},
  {path: '/f', name: 'ff'}
]
console.log(arr2)

我该怎么做才能得到一个arr2数组?

javascript node.js
1个回答
1
投票

您可以将数组合并为一个,而不是使用reduce

这里的想法是 -

  • 首先将两个数组合并为一个数组
  • 现在循环合并数组并使用path作为键
  • 如果对象上已存在键,则将先前值与当前值合并
  • 否则分配一个新值
  • 最后从对象中取出值以获得所需的输出

var arr = [{path: '', meta: {title: 'index'}},{path: '/a', name: 'aa'}];

var arr1 = [{path: '/a', meta: {title:'aa2', hidden: 1}}, {path: '/b', meta: {title:'bb', hidden: 1}} ]  
   
let op = [...arr,...arr1].reduce((op,inp) => {
  let path = inp.path
  op[path] = op[path] || {}
  op[path] = {...op[path], ...inp}
  return op
},{})

console.log(Object.values(op))

UPDATE

var arr = [
 {path: '/a', name: 'aa'},
 {path: '/f', name: 'ff'}
];

var arr1 = [
 {path: '/a', meta: {title:'aa2', hidden: 1}},
 {path: '/b', meta: {title:'bb', hidden: 1}},
 {path: '/c', meta: {title:'cc', hidden: 0}},
 {path: '', meta: {title:'dd', hidden: 0}},
 {path: '', meta: {title:'ee', hidden: 0}}
]

let toBeMerged = arr.reduce((op,inp)=> (op[inp.path] = inp, op),{})

let final = arr1.reduce((op,inp)=>{
  if(toBeMerged[inp.path]){
    op.push({...inp,...toBeMerged[inp.path]})
  } else{
    op.push(inp)
  }
  return op
},[])

Object.entries(toBeMerged).forEach(([key,value])=>{
  let found = final.find(({path})=> path === key )
  if(!found){
    final.push(value)
  }
})

console.log(final)
© www.soinside.com 2019 - 2024. All rights reserved.