Search code examples
javascripthigher-order-functions

Can't access needed object attribute within Javascript Find


I have an object nested in a list of lists that I'm trying to access.

The structure is like this:

list = [[], [{accountID: 123}], [], []]

I can access the needed object by console logging it hard-coded, like this:

console.log(list[0][0].accountID)

However, when I try to look up the object by a needed value using .find(), it always returns undefined:

list.find(e => e[0][0].accountID === 123)

Switching things around like list[0].find(e => e[0].accountID === 123), list[0][0].find etc. doesn't work either.

Not sure what I'm doing wrong. Ideally, I'd also like to avoid hard-coding the indexes, but I've done it here to confirm that the attribute is where I think it is.


Solution

  • find will loop the array, if you use list.find((e) => console.log(e)); you will see the output.

    []
    [ { accountID: 123 } ]
    []
    []
    

    Use e[0]?.accountID to select the object you need.

    list.find((e) => e[0]?.accountID === 123);