假设我们在内存中有两个对象:
const a = [{
id: 123,
width: 5
}, {
id: 345,
width: 10
}];
const b = [{
id: 345,
height: 2
}, {
id: 123,
height: 3
}];
现在我们期望两个对象的连接(数据库连接):
const c = join(a, b);
assert.true(c === {
id: 123,
width: 5,
height: 3
}, {
id: 345,
width: 10,
height: 2
});
有方便的“加入”功能吗?还是我们必须重新设计轮子?
答案 0 :(得分:2)
您可以对同一map
使用id
并将属性收集到新对象中。
const
a = [{ id: 123, width: 5 }, { id: 345, width: 10 }],
b = [{ id: 123, height: 3 }, { id: 345, height: 2 }],
c = [a, b].reduce((m => (r, a) => {
a.forEach(o => {
if (!m.has(o.id)) m.set(o.id, r[r.push({}) - 1]);
Object.assign(m.get(o.id), o);
});
return r
})(new Map), []);
console.log(c);
.as-console-wrapper { max-height: 100% !important; top: 0; }