我正在尝试使用React Table学习多重过滤器。这是我的Demo/Fiddle
我正在尝试消除我的React Table下拉列表中的重复值
<Select
style={{ width: "50%", marginBottom: "20px" }}
onChange={entry => {
this.setState({ select2: entry });
this.onFilteredChangeCustom(
entry.map(o => {
return o.value;
}),
"firstName"
);
}}
value={this.state.select2}
multi={true}
options={this.state.data.map((o, i) => {
return { id: i, value: o.firstName, label: o.firstName };
})}
/>
我在下拉菜单中得到重复的值。请帮助我如何消除下拉菜单中的重复值。
基本上,我正在过滤每列,并且上面的函数基本上处理过滤功能。请看截图。有一个问题-我的Json数组中有些值多次出现。但是在下拉菜单中,它们应该只能出现一次。
编辑1-我想要一个通用的解决方案,该解决方案可以应用于任意数量的下拉菜单。到目前为止,我有两个不错的答案。但是这两个答案都没有概括。我想将此独特功能扩展到所有列。我将有15到20列。这就是为什么我需要一个通用的解决方案。
答案 0 :(得分:1)
var names = this.state.data.map((o, i) => {
return o.firstName
})
var uniqueNames = names.filter(function(i, index){
return names.indexOf(i) >= index
});
https://codesandbox.io/s/40n0jnzk5x 查看firstdropdown的修复程序
助手功能
var uniqueOptions = (objectsArray, objectKey) => {
var a = objectsArray.map((o, i) => {
return o[objectKey]
})
return a.filter(function(i, index){
return a.indexOf(i) >= index
})
}
用于名字下拉菜单(与其他下拉菜单相同)
....
multi={true}
options={this.uniqueOptions(this.state.data, 'firstName').map((name, i) => {
return { id: i, value: name, label: name };
})}
...
理想情况下,您应该在外部渲染中计算该渲染,以防止在每次渲染时重新计算,但您会想到
答案 1 :(得分:1)
尝试一下
const getOptions = propertyName => {
return this.state.data.reduce((accum, elem, i) => {
const accumulator = [...accum];
if (!accumulator.some(e => e.value === elem[propertyName])) {
accumulator.push({
id: i,
value: elem[propertyName],
label: elem[propertyName]
});
}
return accumulator;
}, []);
};
getOptions("FirstName")