I have an array of objects with items (only have name
property) and groups (with a children
property, they may contain items or other groups) and I need to get a full path to needle
value, so in this case it’d be myObj[2]["children"][0]["children"][1]["children"][0]
, plus I’m limited to quite old JS version ECMA 262 (I’m using it inside Photoshop)
var myObj = [
{
"name": "group1",
"children": [
{
"name": "group2",
"children": [
{
"name": "item0"
}]
}]
},
{
"name": "item1"
},
{
"name": "needleGroup",
"children": [
{
"name": "needleNestedGroup",
"children": [
{
"name": "item3"
},
{
"name": "needleNestedDeeperGroup",
"children": [
{
"name": "needle"
}]
}]
}]
}];
My first idea was to transform object to array or arrays so it’d be easier to process, so my object became
[
[
[
"item0"
]
],
"item1",
[
[
"item3",
[
"needle"
]
]
]
];
But.. that’s it. I can’t figure out hot to track down only the indexes I need. Could you please point out a correct direction.
4
Answers
Use a recursive function to look for the item you want. Once the function find it, it will return an array. Each step back of the recursion will
unshift
the object key of this step:The output of this function will be an array of keys leading to
item
. You can easily transform it to the format in the question:Example:
Note: The indexes for the arrays are also formatted as strings, but that won’t be a problem as
someArray["2"]
is equivalent tosomeArray[2]
.Assuming that you have a nested and repetitive pattern of objects in your data-set, the following solution would do the trick for you.
The recursive part of the code will iterate on the children of the current node. The existing strategy here is depending on the
nodePath.value
having at least one element, which indicates that it found the targetted node. Later on, it’ll skip the remaining nodes and would break out of recursion.The
nodePath.value
variable will give you the node-to-root path.I’ve created something you might use. The code below returns an Array of paths to keys, values, objects you are looking for.
See snippet and example to see what you can do.
To make it work you have to pass key and/or value you want to find in element and element which is an Array or Object.
It’s written in newer JS standard but it shouldn’t be a problem to compile it to older standard.
I came accross this issue and took the chance to create find-object-paths, which solves this problem: Finding paths in an object by either keys, values or key/value combinations.
NPM: find-object-paths
Github: getPaths
Example object:
So, the basic usage could be:
See the full documentation here: https://github.com/maugenst/getPaths#readme
BR