admin管理员组文章数量:1394593
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?
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?
Share Improve this question edited Jun 4, 2018 at 1:39 caulitomaz 2,36115 silver badges20 bronze badges asked Jun 3, 2018 at 23:55 SK121212SK121212 331 gold badge2 silver badges6 bronze badges 1- I was gonna post a filter implementation but there is one detail, props are inmutable... is that correct? you want to change the props of the current ponent? – Facundo Larrosa Commented Jun 4, 2018 at 0:03
3 Answers
Reset to default 2You 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 ponent.
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 ponent to provide new/filtered data as props.
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);
本文标签: javascriptreact how to filter an array of objects in propsStack Overflow
版权声明:本文标题:javascript - react: how to filter an array of objects in props - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744096646a2590404.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论