Home:ALL Converter>Javascript - Find path to object reference in nested object

Javascript - Find path to object reference in nested object

Ask Time:2017-04-26T21:43:06         Author:Dragos Ionescu

Json Formatter

How can i recursively search a nested object to find the PATH to an object reference I'm providing?

My original object looks like:

a = {
 b: [
  { children: [...more objects] },
  { children: [] }
  etc..
 ],
 c: [
  { children: [...more objects] },
  { children: [] }
  etc..
 ]
}

I would like to call a function findDeepAndStorePath(a, obj) which would find the object reference and store the path to it in an array of indexes such as: ['b', 0, 1, 2].

Author:Dragos Ionescu,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/43636000/javascript-find-path-to-object-reference-in-nested-object
ibrahim mahrir :

\r\n\r\nfunction findPath(a, obj) {\r\n for(var key in obj) { // for each key in the object obj\r\n if(obj.hasOwnProperty(key)) { // if it's an owned key\r\n if(a === obj[key]) return key; // if the item beign searched is at this key then return this key as the path\r\n else if(obj[key] && typeof obj[key] === \"object\") { // otherwise if the item at this key is also an object\r\n var path = findPath(a, obj[key]); // search for the item a in that object\r\n if(path) return key + \".\" + path; // if found then the path is this key followed by the result of the search\r\n }\r\n }\r\n }\r\n}\r\n\r\nvar obj = {\r\n \"a\": [1, 2, {\"o\": 5}, 7],\r\n \"b\": [0, [{\"bb\": [0, \"str\"]}]]\r\n};\r\n\r\nconsole.log(findPath(5, obj));\r\nconsole.log(findPath(\"str\", obj).split(\".\")); // if you want to get the path as an array you can simply split the result of findPath",
2017-04-26T13:56:10
Nina Scholz :

You could use Object.keys and check the values. If found, then the actual path is returned and the iteration stops. If not, all possible pathes are checked.\n\nThis proposal respects numeric keys off arrays.\n\n\r\n\r\nfunction findPath(a, obj) {\r\n function iter(o, p) {\r\n return Object.keys(o).some(function (k) {\r\n result = p.concat(Array.isArray(o) ? +k : k);\r\n return o[k] === a || o[k] && typeof o[k] === 'object' && iter(o[k], result);\r\n });\r\n }\r\n var result;\r\n return iter(obj, []) && result || undefined;\r\n}\r\n\r\nvar obj = { a: [1, 2, { o: 5 }, 7], b: [0, [{ bb: [0, \"str\"] }]] };\r\n\r\nconsole.log(findPath(5, obj)); // [\"a\", 2, \"o\"]\r\nconsole.log(findPath(\"str\", obj)); // [\"b\", 1, 0, \"bb\", 1]\r\nconsole.log(findPath(42, obj)); // undefined\r\n.as-console-wrapper { max-height: 100% !important; top: 0; }",
2017-04-26T14:10:07
yy