将 map() 替换为 reduce() 函数



我试图将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 : [] }));

最新更新