简体   繁体   中英

Javascript find() method not working for nested object/array/json values

I am trying to figure out why the nested find() method is not working. Here is my data structure

const arr = [
    {id: 1, name: "one"},
    {id: 2, name: "two"},
    {id: 3, name: "three"},
    {id2: [
        {id3: 30, name: "thirty"},
        {id3: 50, name: "fifty"},
        {id3: 70, name: "seventy"}
        ]
    }
]

The idea is to access the id3 values for which I am using the nested find() method like this:

const ret = arr.find(function(el){
    return el.id2.find(function(elps){
        return elps
    })
})

Interestingly, I am intermittently getting two different errors.

  1. TypeError: Cannot read property 'find' of undefined

OR I get

  1. find is not a function...

I also tried using some() method for the second iteration but it returns the same errors.

If I use find() on the parent level(1st iteration) array it works fine like this:

const ret = arr.find(function(el){
        return el.id > 2
})

My question: What is that I am missing in second iteration that the find() method is not working there?

You can use Array.isArray() before implementing the nested find() to avoid using it on an undefined property or property where value isn't an array

It's not really clear what your expected result is so the following returns the main array object that contains a matching sub-array element

 const arr = [ {id: 1, name: "one"}, {id: 2, name: "two"}, {id: 3, name: "three"}, {id2: [ {id3: 30, name: "thirty"}, {id3: 50, name: "fifty"}, {id3: 70, name: "seventy"} ] } ] const res = arr.find(({id2}) => Array.isArray(id2) && id2.find(({id3}) => id3 === 30)) console.log(res)

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