gpt4 book ai didi

javascript - 如何在一个循环中组合/合并/相交两个对象数组?

转载 作者:行者123 更新时间:2023-11-28 17:32:45 25 4
gpt4 key购买 nike

这段代码可以工作,但我觉得一定有更好的方法,而不必使用 Array.find() 两次。

const people = [
{ id: 0, age: 99 },
{ id: 1, age: 54 },
{ id: 2, age: 54 }
];
const roles = [
{ pId: 0, responsabilites: ['make money'] },
{ pId: 1, responsabilites: ['make money', 'complain'] },
{ pId: 4, responsabilites: ['make the world a better place', 'sarcasmm'] },
];

let roomsAndOrders = people.filter(p => {
return roles.find(r => r.pId === p.id);
});
roomsAndOrders = roomsAndOrders.map(p => {
let r = roles.find(r => r.pId === p.id);
return { ...r, ...p };
});

console.log(roomsAndOrders);

最佳答案

只需使用一个.map。您原来的 filter 没有多大意义 - filter 从数组中过滤掉您不需要的元素,但它不会更改元素。您正在从 filter 函数返回对象,并且对象是真实的,因此 filter 实际上不会执行任何操作。

编辑:或者只是以相反的方式映射 - 一次从 roles 映射到 people,而不是从 people 映射到 Angular 色

const people = [
{ id: 0, age: 99 },
{ id: 1, age: 54 },
{ id: 2, age: 54 }
];
const roles = [
{ pId: 0, responsabilites: ['make money'] },
{ pId: 1, responsabilites: ['make money', 'complain'] },
];

const roomsAndOrders = roles.map(role => {
const person = people.find(({ id }) => role.pId === id);
return { ...role, ...person };
});
console.log(roomsAndOrders);

要仅包含 ID 在两个数组中的对象,您必须使用 .reduce 来代替,因为 map 始终返回与原始数组中相同数量的元素数组:

const people = [
{ id: 0, age: 99 },
{ id: 1, age: 54 },
{ id: 2, age: 54 }
];
const roles = [
{ pId: 0, responsabilites: ['make money'] },
{ pId: 1, responsabilites: ['make money', 'complain'] },
{ pId: 4, responsabilites: ['make the world a better place', 'sarcasmm'] },
];

const roomsAndOrders = roles.reduce((accum, role) => {
const person = people.find(({ id }) => role.pId === id);
if (person) accum.push({ ...role, ...person });
return accum;
}, []);
console.log(roomsAndOrders);

关于javascript - 如何在一个循环中组合/合并/相交两个对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49913083/

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