Created
June 4, 2019 13:39
-
-
Save panphora/52e5b4e1f5722f18e1f87d6d0b40b96a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// starting with: object, childObject | |
// goal | |
// - given an object/array and a child object/array, give me the path to the child | |
// some code copied from: https://github.com/moxystudio/js-deep-for-each | |
function isPlainObject (obj) { | |
return Object.prototype.toString.call(obj) === '[object Object]'; | |
} | |
function forEachObject(obj, fn, path) { | |
for (const key in obj) { | |
const deepPath = path ? `${path}.${key}` : key; | |
// Note that we always use obj[key] because it might be mutated by forEach | |
fn.call(obj, obj[key], key, obj, deepPath); | |
deepForEach(obj[key], fn, deepPath); | |
} | |
} | |
function forEachArray(array, fn, path) { | |
array.forEach((value, index, arr) => { | |
const deepPath = `${path}[${index}]`; | |
fn.call(arr, value, index, arr, deepPath); | |
// Note that we use arr[index] because it might be mutated by forEach | |
deepForEach(arr[index], fn, deepPath); | |
}); | |
} | |
function deepForEach(value, fn, path) { | |
path = path || ''; | |
if (Array.isArray(value)) { | |
forEachArray(value, fn, path); | |
} else if (isPlainObject(value)) { | |
forEachObject(value, fn, path); | |
} | |
} | |
function getPathOfChildObject (parentObj, childObj) { | |
let path; | |
deepForEach(parentObj, function (value, key, subject, currentPath) { | |
if (value === childObj) { | |
path = currentPath; | |
} | |
}) | |
return path; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment