作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这段代码可以工作,但我觉得一定有更好的方法,而不必使用 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/
我是一名优秀的程序员,十分优秀!