如何在javascript中比较两个对象数组?

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

我想比较这两个对象数组并获得与注释相同的结果。我的解决方案是覆盖迭代,但我还没有想出更好的解决方案。

   const arr1 = [
     {key: 'cat', name: 'john' },
     {key: 'dog', name: 'james' },
     {key: 'dog', name: 'kane' }
   ];
   const arr2 = [
    {kind: 'cat', sound: 'meow', size: 'small', state: 'angry' },
    {kind: 'dog', sound: 'woof', size: 'big', state: 'happy'  },
    {kind: 'pig', sound: 'oink', size: 'medium', state: 'sad' },
   ];

   const result = arr1.map((ar) => {
     const data = arr2.find(ar2=> {
       return ar.key === ar2.kind;
     })
     const {sound} = data;
     return Object.assign(ar, {sound});
   });

   console.log(result);

   /* result
   [
     {key: 'cat', sound: 'meow', name: 'john'},
     {key: 'dog', sound: 'woof', name: 'james'},
     {key: 'dog', sound: 'woof', name: 'kane'},
   ]
   */

我想知道比这更好的解决方案。我该如何解决?请让我知道。

javascript arrays algorithm
1个回答
0
投票

我首先创建一个soundsByAnimalName对象,其键是动物的名字,值是它们发出的声音,然后.map第一个数组,然后在该对象上查找animal.key属性:

const arr1 = [
  {key: 'cat', name: 'john' },
  {key: 'dog', name: 'james' },
  {key: 'dog', name: 'kane' }
];
const arr2 = [
  {kind: 'cat', sound: 'meow', size: 'small', state: 'angry' },
  {kind: 'dog', sound: 'woof', size: 'big', state: 'happy'  },
  {kind: 'pig', sound: 'oink', size: 'medium', state: 'sad' },
];
const soundsByAnimalName = arr2.reduce((a, { kind, sound }) => {
  a[kind] = sound;
  return a;
}, {});

const result = arr1.map(
  animal => ({ ...animal, sound: soundsByAnimalName[animal.key] })
);
console.log(result);
© www.soinside.com 2019 - 2024. All rights reserved.