Reputation: 948
I am learning about React basics and came across this challenge that gave me a lot of trouble.
I have list of items in 'state' function. When I am listing them on the screen, I would like to list the ones that have 'found=0' value. I have tried to search in the web, tried applying so many different solutions including the ones from here in stackoverflow but I kept getting so many different errors so I couldn't make it work.
This is my 'state' function saved in my App.js file:
state = {
counters: [
{ id: 1, title: "Soymilk", found: 1, value: 0 },
{ id: 2, title: "Mushroom", found: 0, value: 0 },
{ id: 3, title: "Tomatoes", found: 1, value: 0 },
{ id: 4, title: "Potatoes", found: 0, value: 0 },
{ id: 5, title: "Meat", found: 0, value: 0 },
{ id: 6, title: "Beans", found: 0, value: 0 },
{ id: 7, title: "Bread", found: 0, value: 0 }
]};
And this is the counter.jsx code that displays my items:
render() {
return (
<div className="list-group">
<span className="font-weight-bold list-group-item list-group-item-action flex-column align-items-start">
{this.props.counter.title}
<span className="font-weight-normal text-secondary float-right">
{this.foundMessage()}
</span>
</span>
<div className="row">
<button
onClick={() => this.props.onFind(this.props.counter)}
className="btn btn-sm col-3 btn-primary col-6"
>
Found it!
</button>
<button
onClick={() => this.props.onDelete(this.props.counter.id)}
className="btn btn-danger btn-sm col-6"
>
No more needed!
</button>
</div>
</div>
);}}
Upvotes: 2
Views: 717
Reputation: 428
You can use .filter
and .map
Array methods, but this isn't the only way.
Here is an example which does exactly what you need.
Upvotes: 0
Reputation: 739
you can use map function which returns a new array with operation taking place in its callback for every element.
function filterCounters(){
let newCounters = [];
counter.map(element=>{
if(element.found === 0 ){
newCounters.push(element);
}
})
return newCounters;
}
Upvotes: 0
Reputation: 1217
You can use the filter
function of the array. Like this
var ages = [32, 33, 16, 40];
checkObj = (obj) => {
return obj > 16;
}
let val = ages.filter(checkObj)
//val contains the filtered array with found == 0
// or you can use this way
let val = this.state.counters.filter((obj)=>{
return obj.found == 0;
})
Hope it helps, If I don't understand your problem. Please reply
Upvotes: 0
Reputation: 4961
You can filter your data,
like this,
let filteredData= this.state.counters.filter(item=>item.found==0);
this.setState({counters:filteredData});
Upvotes: 2