Reputation: 33
I have props
with following data
test1: abc
id: 1
myArray: Array(3)
0: {a:abc, b:cde, aid: 1}
1: {e:age, f:ade, aid: 2}
2: {t:are, h:had, aid: 1}
I want to filter props and update array to have only the values that match id
and aid
So the props should look like below:
test1: abc
id: 1
myArray: Array(3)
0: {a:abc, b:cde, aid: 1}
2: {t:are, h:had, aid: 1}
How can i do that?
Upvotes: 3
Views: 15985
Reputation: 5669
You will get the filtered data by using,
const filteredData = this.props.myArray.filter(item => item.aid === 1)
However props is only readable. You will have to eigther dispatch or update parent component to provide new/filtered data as props.
Upvotes: 1
Reputation: 2341
You can use the filter Array method
let myArray = [{a:"abc", b:"cde", aid: 1},
{e:"age", f:"ade", aid: 2},
{t:"are", h:"had", aid: 1}]
const result = myArray.filter(item => item.aid === 1)
console.log(result)
But take in consideration that props are immutable.
If you wish to change this prop
permanently you will have to update it in the parent component.
Upvotes: 2
Reputation: 6556
you can use Array.filter()
// match both a AND aid
const result = myArray.filter(obj => (obj.a === test1 && obj.aid === id);
// match either a OR aid
const result = myArray.filter(obj => (obj.a === test1 || obj.aid === id);
Upvotes: 0