【问题标题】:How to compare two object array in javascript?如何在javascript中比较两个对象数组?
【发布时间】:2025-12-04 12:25:02
【问题描述】:

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

   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'},
   ]
   */

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

【问题讨论】:

  • 这不是一个好的风格,回答*.com/questions/58162775/…并删除问题。
  • 该链接出现页面未找到问题。
  • 对,您缺少查看已删除问题的代表,但它基本上是相同的问题,答案来自this question的答案。所以你的尝试是一个副本。

标签: javascript arrays algorithm


【解决方案1】:

我首先创建一个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);

【讨论】:

  • 请注意,创建soundsByAnimalName 的映射会将计算复杂度降低到O(n) - 像.find 这样的嵌套循环具有O(n ^ 2) 的复杂度,这是不必要的
【解决方案2】:

你的想法是对的。如果你的意思是“更好”是一种更短的写法,那就是:

您可以使用 ... 扩展运算符将键添加到第一个数组的 json 中。并使用||运算符来处理没有匹配值的情况。

const arr1 = [{
    key: 'cat',
    name: 'john'
  },
  {
    key: 'dog',
    name: 'james'
  },
  {
    key: 'dog',
    name: 'kane'
  },
  {
    key: 'lama',
    name: 'cartman'
  }
];

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 ret = arr1.map(x => {
  const {
    sound = '',
    size = '',
  } = (arr2.find(y => y.kind === x.key) || {});

  return ({
    ...x,
    
    sound,
    size,
  });
});

console.log(ret);

【讨论】:

  • 感谢您的回答,我有一个问题。如果你必须增加尺寸,你会怎么做?
最近更新 更多