简体   繁体   English

在reactjs中映射和过滤数组

[英]Doing map and filter an array in reactjs

I have a list of object: 我有一个对象列表:

a = [{number:1},{category:[abc, cde]},{class:2}],
    [{number:2},{category:[abc, def]},{class:3}],
    [{number:3},{category:[def]},{class:4}]

below is my code: 下面是我的代码:

            b
            .filter((a, index) => (a.category === 'def'))
            .map((a, index) => (
                  <div>{a.number}</div>
               )
            )

I need to list down object from 'a' which contain category = 'def'. 我需要从包含类别='def'的'a'列出对象。 Seems like I'm unable to filter it because my 'category' is in array format. 好像我无法过滤它,因为我的“类别”是数组格式。 How do you guys fix it? 你们如何解决?

只需检查def是否在数组中,如:

a.category.includes('def')
b
.filter((v,i) => (v.category.includes('def')))
.map((v,i) => (
     <div>{v.number}</div>
))

Your objects are stored as an array of objects, which means you can't "key in" to check. 您的对象存储为对象数组,这意味着您无法“键入”进行检查。 So you have to check all of the elements of the array to see if 1. the key category exists and 2. see if def is in the object that contains category . 因此,您必须检查数组的所有元素,以查看是否1.关键category存在,以及2.看def是否在包含category的对象中。

Array#includes has an older brother that is often overlooked. Array#includes有一个常被忽视的哥哥。 Array#some , which accepts a callback that will do what you need. Array#some ,它接受将执行您需要的回调。

Then you have to use Array#find to traverse the filtered arrays again to find the object that has the key number and then print that value. 然后,您必须使用Array#find再次遍历过滤后的数组,以找到具有键number的对象,然后打印该值。 You can also do this manually by using the index number of those objects, but it's far less robust. 您也可以通过使用这些对象的索引号手动执行此操作,但是它的健壮性要差得多。

 a = [[{number:1},{category:['abc', 'cde']},{class:2}], [{number:2},{category:['abc', 'def']},{class:3}], [{number:3},{category:['def']},{class:4}]] h = a.filter((arr) => { return arr.some((obj) => { if (obj.category) { return obj.category.includes('def') } else { return false } }) }) console.log(h) j = h.map((arr) => { let numObject = arr.find((obj) => ('number' in obj)); if (numObject) { return numObject.number } else { return //something } }) console.log(j) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM