如何通过与id进行比较来合并三个不同的数组?在Angular 6中
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何通过与id进行比较来合并三个不同的数组?在Angular 6中相关的知识,希望对你有一定的参考价值。
阵列:
array1 = [{id:1, name:"raju"},{id:2, name:"ravi"},{id:4, name:"john"},{id:6, name:"jack"}];
array2= [{id:1, degree:"b.com"},{id:3, degree:"b.a"},{id:4, degree:"c.a"},{id:5, degree:"horticulture"}];
array3= [{id:1, age:20},{id:3, age:21},{id:6, age:27},{id:7, age:25}];
要求的结果是:
resultarray = [
{id:1, name: "raju", degree:"b.com",age:20},
{id:2, name: "ravi"},
{id:3, degree:"b.a", age:21},
{id:4, name:"john", degree:"c.a"},
{id:5, degree:"horticulture"},
{id:6, name:"jack", age:27},
{id:7, age:25}
]
我尝试了不同的功能,并尝试了两个数组,但无法合并没有id比较的对象..
答案
你可以使用reduce和destructuring
这里的想法是
- 首先将所有数组合并到一个数组中。
- 现在使用reduce我们创建
id
作为op
对象的关键 - 如果
id
密钥已经在那里我们合并inp
和op[inp.id]
- 如果id不存在,我们创建一个值为
inp
的新密钥
let array1 = [{id:1, name:"raju"},{id:2, name:"ravi"},{id:4, name:"john"},{id:6, name:"jack"}];
let array2= [{id:1, degree:"b.com"},{id:3, degree:"b.a"},{id:4, degree:"c.a"},{id:5, degree:"horticulture"}];
let array3= [{id:1, age:20},{id:3, age:21},{id:6, age:27},{id:7, age:25}];
let temp = [...array1,...array2,...array3]
let op = temp.reduce((op,inp)=>{
op[inp.id] = op[inp.id] || inp
op[inp.id] = {...op[inp.id],...inp}
return op
},{})
console.log(Object.values(op))
另一答案
可能的解决方案:
let array1 = [{id:1, name:"raju"},{id:2, name:"ravi"},{id:4, name:"john"},{id:6, name:"jack"}];
let array2= [{id:1, degree:"b.com"},{id:3, degree:"b.a"},{id:4, degree:"c.a"},{id:5, degree:"horticulture"}];
let array3= [{id:1, age:20},{id:3, age:21},{id:6, age:27},{id:7, age:25}];
let resp = [].concat(array1, array2, array3).reduce((acc, ele) => {
let obj = acc.find(x => x.id === ele.id);
return obj ? (Object.keys(ele).forEach(x => obj[x] = ele[x]), acc) : acc.concat(ele);
}, [])
console.log(resp)
另一答案
会有比这更好的解决方案,但这是我尝试过的:
将3个数组合并为一个:
let array = [...array1, ...array2, ...array3]
循环遍历项目,然后将值放到“对象”
let object = {}
array.forEach((item) => {
object[item.id] = { ...object[item.id],...item}})
最后的称呼
result = Object.values(object)
对象变量将包含
object = { '1': { id: 1, age: 20, name: 'raju', degree: 'b.com' },
'2': { id: 2, name: 'ravi' },
'3': { id: 3, age: 21, degree: 'b.a' },
'4': { id: 4, degree: 'c.a', name: 'john' },
'5': { id: 5, degree: 'horticulture' },
'6': { id: 6, age: 27, name: 'jack' },
'7': { id: 7, age: 25 } }
结果变量将包含
result = [ { id: 1, age: 20, name: 'raju', degree: 'b.com' },
{ id: 2, name: 'ravi' },
{ id: 3, age: 21, degree: 'b.a' },
{ id: 4, degree: 'c.a', name: 'john' },
{ id: 5, degree: 'horticulture' },
{ id: 6, age: 27, name: 'jack' },
{ id: 7, age: 25 } ]
以上是关于如何通过与id进行比较来合并三个不同的数组?在Angular 6中的主要内容,如果未能解决你的问题,请参考以下文章