Created
April 1, 2019 15:59
-
-
Save panphora/9df8f0c56f3ff23013b5fc2e5a45fd7d to your computer and use it in GitHub Desktop.
This file contains 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
// DESCRIPTION: | |
// ============ | |
// loops through all items in a nested object/array | |
// | |
// USE: | |
// === | |
// forEachNestedData({currentItem, callback}); | |
// | |
// OUTPUT: | |
// ====== | |
// {isRoot, isString, isObject, isArray, keyName, index, value, parent, path} | |
// | |
// OUTPUT DESCRIPTION: | |
// ================== | |
// isRoot: is this the object/array that was passed in | |
// isString: is the current value a string | |
// isObject: is the current value an object | |
// isArray: is the current value an array | |
// keyName: the keyName you can pass in to parent to get the current value | |
// index: the index you can pass in to parent to get the current value | |
// value: the current value | |
// parent: the parent object or array | |
// path: an array of keys and/or indeces that if sequentially passed to the root object/array would output the current value | |
export default function forEachNestedData ({currentItem, keyName, index, parent, path, callback}) { | |
path = path || []; | |
let isRoot = path.length === 0; | |
let isArray = Array.isArray(currentItem); | |
let isObject = !isArray && typeof currentItem === "object" && currentItem !== null; | |
let isString = typeof currentItem === "string"; | |
callback({isRoot, isObject, isArray, isString, keyName, index, value: currentItem, parent, path: path.slice()}); | |
if (isArray) { | |
currentItem.forEach((value, index) => { | |
let pathCopy = path.slice(); | |
pathCopy.push(index); | |
forEachNestedData({currentItem: value, index, parent: currentItem, path: pathCopy, callback}); | |
}); | |
} else if (isObject) { | |
Object.keys(currentItem).forEach((keyName) => { | |
let pathCopy = path.slice(); | |
pathCopy.push(keyName); | |
forEachNestedData({currentItem: currentItem[keyName], keyName, parent: currentItem, path: pathCopy, callback}); | |
}); | |
} | |
} | |
// e.g. | |
// getKey({a:{b:2}}, "a", "b") => 2 | |
// getKey({a:{b:2}}, "a") => {b:2} | |
// getKey({a:{b:2}}, "a", "c") => undefined | |
// getKey({a:{b:2}}, "a", "c", "d") => null | |
export function getKey (obj, ...keys) { | |
try { | |
return keys.reduce((memo, keyName) => { | |
return memo[keyName]; | |
}, obj); | |
} catch (e) { | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment