如何通过与id比较来合并三个不同的数组?在Angular 6中

时间:2019-03-22 04:42:18

标签: javascript typescript angular6

数组:

 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进行比较的对象。

3 个答案:

答案 0 :(得分:7)

您可以使用reducedestructuring

这里的想法是

  • 首先将所有数组合并到一个数组中。
  • 现在使用reduce在id对象中创建op作为键
  • 如果已经存在id键,则我们将inpop[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))

答案 1 :(得分:2)

可能的解决方案:

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)

答案 2 :(得分:1)

会有比这更好的解决方案,但这是我尝试过的:

将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 } ]