js-object-utilities
Version:
JavaScript utilities for nested objects
41 lines (40 loc) • 1.27 kB
JavaScript
;
const originalKey = "object";
module.exports = (object, searchKey) => {
const keys = [];
const stack = [];
const stackSet = new Set();
const detected = [];
function detect(object, key) {
if (object && typeof object !== "object") {
return;
}
if (stackSet.has(object)) { // it's cyclic! Print the object and its locations.
const oldIndex = stack.indexOf(object);
const l1 = keys.join(".") + "." + key;
// const l2: string = keys.slice(0, oldIndex + 1).join(".");
const currentKey = l1.replace(`${originalKey}.`, "");
if (!searchKey || currentKey === searchKey) {
detected.push(currentKey);
return;
}
else {
return;
}
}
keys.push(key);
stack.push(object);
stackSet.add(object);
for (const k in object) { //dive on the object's children
if (Object.prototype.hasOwnProperty.call(object, k)) {
detect(object[k], k);
}
}
keys.pop();
stack.pop();
stackSet.delete(object);
return;
}
detect(object, originalKey);
return detected;
};