【发布时间】:2020-05-14 05:07:56
【问题描述】:
当我的logo 的名称与projects 中的items 对象在reduce 函数的帮助下匹配时,我正在输出projects 的匹配值。但是,每当我点击多个与project.items 匹配的徽标时,我都会渲染重复项。
这是我的代码:
logos.reduce((acc, logo) => {
if (logo.active) {
Object.values(projects).forEach((proj) => {
if (Object.values(proj.items).includes(logo.name)) {
console.log(acc)
acc.push((<Project title={proj.title} routeName={proj.routeName} items={proj.items} description={proj.description}/>));
}
});
}
return acc
}, [])
我的第一个想法是创建另一个数组,运行一个 for 循环并遍历这些值,例如:filteredValues[i].props.title,然后将该循环的内容推送到一个数组中。我像这样在该数组上运行reduce,但无法消除重复项:
const filteredArr = arr.reduce((acc, current) => {
const x = acc.find(item => item.title === current.title);
if (!x) {
return acc.concat([current]);
} else {
return acc;
}
}, []);
无论如何,这是我用来渲染我的Project 组件的acc 的输出
【问题讨论】:
标签: javascript arrays reactjs foreach mapreduce