I have the following object:
const obj = {
alphas: {
top: [{name: "q"}, {name: "w"}],
middle: [{name: "a"}, {name: "s"}],
bottom: [{name: "z"}, {name: "x"}],
},
numbers: {
low: [{name: "1"}, {name: "2"}, {name: "3"}],
high: [{name: "1000"}, {name: "2000"}],
}
}
I need the nested indexes of the name
.
For instance, if I'm looking for "s"
the result should be the array [0, 1]
:
0
because"s"
is in the first category (alphas
)1
because"s"
is in the second subcategory (middle
).
I'm able to find the indexes in separate loops:
const categoryIndex = Object.keys(obj).findIndex(
cat => Object.keys(obj[cat]).some(
subcat => obj[cat][subcat].some(
key => key.name === "s")));
const categoryName = Object.keys(obj)[categoryIndex];
const subcategoryIndex = Object.keys(obj[categoryName]).findIndex(
subcat => obj[categoryName][subcat].some(key => key.name === "s"));
const result = [categoryIndex, subcategoryIndex];
https://jsfiddle.net/7w523ojn/
Having two separate loops may cost too much so I'm looking for a way to get indexes at once. Something like this:
[categoryIndex , subcategoryIndex] = ...
Is there a way to get nested indexes at once? Solutions involving Lodash, Ramda and whatnot are also welcome. Thank you.