todoList.js
const todoList = [
{category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
{category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},
{category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'},
{category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
{category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
{category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}
];
export default todoList
FilterTableProdcTable.js
class FilterableProductTable extends React.Component{
render(){
const aw = []
todoList.forEach(elem=>{
if(aw.indexOf(elem.category) === -1){
aw.push(
<li key={elem.name}> {elem.category}</li>
)
}
})
return(
<div>
{aw}
</div>
)
}
}
结果仍然相同,所有重复的值仍显示在我的屏幕上。有人可以帮我吗?
对我的英语不好对不起,但谢谢大家
答案 0 :(得分:0)
const uniqueTodos = todoList.filter((todo,index) => {
return index === todoList.findIndex(obj => {
return JSON.stringify(obj) === JSON.stringify(todo);
});
});
还更改您的数据。该数据集中没有什么唯一的。
此外,此代码仅在对象与所有属性相同时才将其删除。可以只考虑一种属性。
const uniqueTodos = todoList.filter((todo,index) => {
return index === todoList.findIndex(obj => {
return obj.category === todo.category;
});
});
class FilterableProductTable extends React.Component{
render(){
const aw = []
uniqueTodos.forEach(todo => {
aw.push(<li key={todo.name}> {todo.category}</li>)
})
return(
<div>
{aw}
</div>
)
}
}
我还对您的数据集做了一些更改以进行测试。
const todoList = [
{category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
{category: 'Sporting Goods', price: '$29.99', stocked: true, name: 'Basketball'},
{category: 'Sporting Goods', price: '$29.99', stocked: true, name: 'Basketball'},
{category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
{category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
{category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'}
];
export default todoList
答案 1 :(得分:0)
您的代码会很好,唯一的问题是您的aw
数组将被li
属性填充,它们不是包含elem.category
的字符串。也许,如果您跟踪不同的数组,则可以检查indexOf。您还可以在innerHTML
属性上使用textContent
或li
。也许考虑这样的事情:
const aw = [];
const categories = [];
todoList.forEach(elem=>{
if(!~categories.indexOf(elem.category)) { // tilde changes the result of indexOf to a boolean
aw.push(
<li key={elem.name}> {elem.category}</li>
)
categories.push(elem.category)
}
})