我试图将map
替换为reduce
但没有成功。你能帮我重写这个代码吗:
this.tares = this.tares
.map(tare => {
let suppliers = [];
this.organizations.forEach(organization => {
if (organization.tare_ids.indexOf(tare.id) !== -1) {
suppliers = suppliers.concat(tare.suppliers);
}
});
return { ...tare, suppliers };
});
我的supplier
变量作为reduce
函数的累加器参数,但在这种情况下,我不知道如何应用reduce
。嵌套数组使我崩溃。
您可以为所有id
获取一个 Set,并将数组映射到一个对象并检查id
是否存在。
var ids = this.organizations.reduce(
(s, { tare_ids }) => tare_ids.reduce((t, id) => t.add(id), s),
new Set
);
this.tares = this.tares.map(tare => ({ ...tare, suppliers: ids.has(tare.id) ? tare.suppliers : [] }));