Skip to content

Instantly share code, notes, and snippets.

@nathan5x-zz
Last active December 17, 2018 04:11
Show Gist options
  • Save nathan5x-zz/0ee938d2ff16cb1ea95b8e3122a316f9 to your computer and use it in GitHub Desktop.
Save nathan5x-zz/0ee938d2ff16cb1ea95b8e3122a316f9 to your computer and use it in GitHub Desktop.
Get deep property values from JavaScript objects by passing key path as an Array
const data = {
foo: {
bar: {
cc: {
str: "Hello I'm deep"
},
dd: "Just a level up",
},
dd: {
cc: "Just another level up"
}
},
bar: {
dd: {
foo: {
str: "I'm foo string"
}
}
}
};
Object.defineProperty(Object, "getProp", {
writeable: false,
configurable: false,
enumerable: false,
value: function getProp(collection, keyMap, ifNotMsg) {
if (typeof collection !== "object") {
return ifNotMsg || "Collection not valid";
}
if (typeof keyMap !== "object" || !Array.isArray(keyMap)) {
return "Keymap not valid";
}
let tempResultObj;
let firstKey = keyMap[0];
let keyMapLength = keyMap.length;
if(keyMapLength === 0 || firstKey === "") {
return "Key map is empty";
}
if (!collection.hasOwnProperty(firstKey)) {
return ifNotMsg;
} else {
tempResultObj = collection[firstKey];
if (keyMapLength == 1) {
return tempResultObj;
}
}
for (let i = 1; i < keyMapLength; i++) {
let currentKey = keyMap[i];
if (typeof tempResultObj === "object" && tempResultObj.hasOwnProperty(currentKey)) {
tempResultObj = tempResultObj[currentKey];
if (i === keyMapLength - 1) {
return tempResultObj;
}
} else {
return ifNotMsg;
}
}
}
});
let tc1 = Object.getProp(data, ['foo', 'bar', 'cc', 'str'], 'Not available.');
let tc2 = Object.getProp(data, ['foo', 'cc', 'cc'], 'Not available.');
let tc3 = Object.getProp(data, ['foo', 'bar', 'dd'], 'Not available.');
let tc4 = Object.getProp(data, ['foo', 'bar'], 'Not available.');
let tc5 = Object.getProp(data, ['bar', 'foo'], 'Not available.');
let tc6 = Object.getProp(data, ['bar'], 'Not available.');
console.log("Test case: data, ['foo', 'bar', 'cc', 'str'] -->" + tc1);
console.log("Test case: data, ['foo', 'cc', 'cc'] -->" + tc2);
console.log("Test case: data, ['foo', 'bar', 'dd'] -->" + tc3);
console.log("Test case: data, ['foo', 'bar'] -->" + JSON.stringify(tc4));
console.log("Test case: data, ['bar', 'foo'] -->" + tc5);
console.log("Test case: data, ['bar'] -->" + tc6);
// Consol.log output
"Test case: data, ['foo', 'bar', 'cc', 'str'] -->Hello I'm deep"
"Test case: data, ['foo', 'cc', 'cc'] -->Not available."
"Test case: data, ['foo', 'bar', 'dd'] -->Just a level up"
"Test case: data, ['foo', 'bar'] -->{\"cc\":{\"str\":\"Hello I'm deep\"},\"dd\":\"Just a level up\"}"
"Test case: data, ['bar', 'foo'] -->Not available."
"Test case: data, ['bar'] -->[object Object]"
@nathan5x-zz
Copy link
Author

Let me know if there are any other test cases that you want to cover.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment