I have a javascript object width depth.
I need to know the exact path from this key within the object ex: “obj1.obj2.data1”
I already know the key is data1, the value is 123.
My javascript object look like this
{
obj1: {
obj2: {
data1: 213,
data2: "1231",
obj3: {
data: "milf"
}
}
},
obj4: {
description: "toto"
}
}
How could I achieve that ?
here is a jsfiddle : http://jsfiddle.net/3hvav8xf/8/
I am trying to implement getPath.
Here you go!
Rerutns path if found, else returns undefined.
I have only tested it with objects & comparison is very strict(ie: used
===
).Update:
Updated version that takes key as an argument.
I think recursive function can help to you (Updated version, to check value)
JSON Object can be handled in JavaScript as associative array.
So You can cycle through and store indexes of "parents" in some variables.
Assume the whole object to be stored in variable called obj.
Hope answer was helpful.
The following finds the path in any level of nested objects. Also with arrays.
It returns all the paths found, which is something you want if you have keys with the same name.
I like this approach because it works with
lodash
methodsget
andset
out-of-the-box.Try it here – https://jsfiddle.net/spuhb8v7/1/
If you want the result to be a single key (first encountered), you can change the
results
to be a string and if defined, then return the function with it.I ended up with the following function, that works with nested objects/arrays :