I have the following nested object:
const sites = [
{
"name": "name1",
"list": [
{
"id":1,
"name": "Year",
"type": "int"
}
]
}
]
I would like to check if one item is present in the object by checking the id:
const item1 = {
"id":1,
"name": "Year",
"type": "int"
}
const item2 = {
"id":2,
"name": "Month",
"type": "int"
}
So I do:
sites.some(i => i.list.some(j => j.id === item1.id)) //True
sites.some(i => i.list.some(j => j.id === item2.id)) //False
Is there a better way to do this query without using so many .some?
2
Answers
Your
.some
approach is perfectly reasonable. Use functions to keep DRY.If you want to use Lodash, it can make it a little more negligibly short.
2
some()
‘s are the fastest way for 2 checks. So it’s totally ok.If you have many items in the lists and check many items I would suggest gather IDs in a
Set
, then the checking is trivial: