gpt4 book ai didi

javascript - 使用映射查找和函数覆盖数组中的对象

转载 作者:行者123 更新时间:2023-12-01 02:32:12 24 4
gpt4 key购买 nike

人,

我正在练习 .map 和 .find。我想映射 arr1 并在 id 匹配时用 arr2 覆盖此 (arr1) 中的每个对象。

<script>

const arr1 = [
{id: '1', name: 'A', surName: 'A', age: 30},
{id: '2', name: 'B', surName: 'B', age: 40},
{id: '3', name: 'C', surName: 'C', age: 50}
];

const arr2 = [
{id: '1', name: 'D', surName: 'D', age: 60, nickName: 'DD'},
{id: '5', name: 'E', surName: 'E', age: 70, nickName: 'EE'},
{id: '3', name: 'F', surName: 'F', age: 80, nickName: 'FF'}
];


let newArr = arr1.map(obj => arr2.find(o => o.id === obj.id) || obj);

console.log(newArr);

</script>

结果:

0: {…}
age: 60
id: "1"
name: "D"
nickName: "DD"
surName: "D"

1: {…}
age: 40
id: "2"
name: "B"
surName: "B"

2: {…}
age: 80
id: "3"
name: "F"
nickName: "FF"
surName: "F"

但是,我想为不匹配的属性添加值为“none”的属性 nickName,例如

1: {…}
age: 40
id: "2"
name: "B"
surName: "B"

对于结果数组:newArr

我真的被困住了。我找不到路。作为学徒,我将不胜感激的帮助。非常感谢

最佳答案

当另一个数组中不存在 ID 时,您可以使用 coalescing 分配 nickName 的默认值。

const arr1 = [{id: '1', name: 'A', surName: 'A', age: 30},{id: '2', name: 'B', surName: 'B', age: 40},{id: '3', name: 'C', surName: 'C', age: 50}],
arr2 = [{id: '1', name: 'D', surName: 'D', age: 60, nickName: 'DD'},{id: '5', name: 'E', surName: 'E', age: 70, nickName: 'EE'},{id: '3', name: 'F', surName: 'F', age: 80, nickName: 'FF'}];

var result = arr1.map(o => {
var {nickName} = arr2.find(({id}) => id === o.id) || {nickName: 'none'};
return Object.assign({}, o, {nickName});
});
console.log(result);

关于javascript - 使用映射查找和函数覆盖数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48236418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com