Mike Manfrin
Mike Manfrin

Reputation: 2762

Lodash way of finding if deep object has a specific key value, not knowing if deep object exists?

There are a fair number of questions asking how to find if an object has a specific key value, but they are all plain JS implementations and couldn't find an answer that was Lodash-ey.

I know in lodash I can find deep objects without chaining &&s with

_.get(myObj, "some.Deep.Object")

I also know I can find where a value for a key matches what I'm trying to find in a collection with

_.find(myCollection, {id: THE_VALUE_I_WANT}

My question is: is there a way to do both of these in one go?

I tried

_.find("myObj.some.Deep.Object", {id: THE_VALUE_I_WANT})

but find needs an actual object to work with. I know I could nest the commands inside each other, do something like

_.find(_.get(myObj, "some.Deep.Object", []), {id: THE_VALUE_I_WANT})

I have a suspicion there is something I am missing in Lodash's docs that would do this with one call, rather than needing to nest two calls.

Upvotes: 0

Views: 1053

Answers (1)

kalley
kalley

Reputation: 18472

You can do it with the following:

_.find(myCollection, ['myObj.some.Deep.Object.id', THE_VALUE_I_WANT])

Upvotes: 1

Related Questions