【发布时间】: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