我有两个数组,两个数组都有数据,但是都有field_id,所以我想合并数组

时间:2019-08-08 12:30:33

标签: javascript typescript

我有两个数组,我想合并两个数组,但数组1与2合并并创建新数组,新数组中也有array1和array2数据,但没有重复的条目。

我尝试使用concat函数,但没有用

数组1:

[[id: 45,
    name: Tv,
    active: false,
], [id: 56,
    name: Car,
    active: true,
][id: 60,
    name: bus,
    active: false,
]]

数组2:

[[id: 45,
        company: sony,
        size: 32,
        price: 451
    ],
    [id: 56,
        company: suzuki,
        size: L,
        price: 3000
    ]]

我想要这样的数据:

[[id: 45,
        name: tv,
        active: false,
        company: sony,
        size: 32,
        price: 451
    ],
    [id: 56,
        name: car,
        active: true,
        company: suzuki,
        size: M,
        price: 3000
    ],
    id: 60,
    name: bus,
    active: false]]

但是如果您要使用此数据在javascript中的对象中创建对象

2 个答案:

答案 0 :(得分:1)

您可以使用以下方法来合并任意数量的数组:

  • 将所有项目合并到一个数组中
  • 获取唯一ID的数组
  • 合并所有具有相同ID的对象

const arr1 = [{ id: 45, name: "Tv", active: false }, { id: 56, name: "Car", active: true }, {id: 60, name: "bus", active: false }];
const arr2 = [{ id: 45, company: "sony", size: 32, price: 451 }, { id: 56, company: "suzuki", size: "L", price:3000 }];
const arr3 = [{ id: 45, type: 'electronics' }];

const mergeArrays = (...arrays) => {
  const all = [].concat.apply([], arrays);
  const ids = new Set(all.map(item => item.id));
  return Array.from(ids).map(id =>
    Object.assign({}, ...all.filter(item => item.id === id))
  );
};

console.log(mergeArrays(arr1, arr2, arr3));

答案 1 :(得分:0)

您可以使用reduce形成一个新的对象数组。在迭代元素时,您可以使用find从另一个数组中获取具有相同id的对象。我们通过解构合并当前对象和数组2中的对象。

var ar1 = [{id:45,name:"Tv",active:!1,},{id:56,name:"Car",active:!0},{id:60,name:"bus",active:!1}],
    ar2 = [{id:45,company:"sony",size:32,price:451},{id:56,company:"suzuki",size:"L",price:3000}];

let res = ar1.reduce((a,c) => {
               let tmp = ar2.find(({id}) => id == c.id);
               tmp ? a.push({...c, ...tmp}) : a.push(c);
               return a;
             },[])

console.log(res)

单线:

let res = ar1.reduce((a,c) => (a.push({...c, ...ar2.find(({id}) => id == c.id)}),a),[])