第一个数组:
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数组?
您可以将数组合并为一个,而不是使用reduce
这里的想法是 -
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)