Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// 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
You can’t perform that action at this time.