简体   繁体   中英

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'. 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 .

Array#includes has an older brother that is often overlooked. Array#some , which accepts a callback that will do what you need.

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. 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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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