我想比较这两个对象数组并获得与注释相同的结果。我的解决方案是覆盖迭代,但我还没有想出更好的解决方案。
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'},
]
*/
我想知道比这更好的解决方案。我该如何解决?请让我知道。
我首先创建一个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);