Get Object Value from String Path
const obj = {
a: {
b: {
c: [1, 2, 3],
},
},
};
console.log(get(obj, "a.b.c"));
console.log(get(obj, "a.b.c.0"));
console.log(get(obj, "a.b.c[1]"));
console.log(get(obj, ["a", "b", "c", "2"]));
console.log(get(obj, "a.b.c[3]"));
console.log(get(obj, "a.c"));
// [ 1, 2, 3 ]
// 1
// 2
// 3
// undefined
// undefined
function get(object, stringPath) {
if (stringPath === "" || stringPath.length === 0) {
return;
}
const excludeCharacters = ["[", "]", "."];
const keys = [];
for (let i = 0; i < stringPath.length; i++) {
if (!excludeCharacters.includes(stringPath[i])) {
keys.push(stringPath[i]);
}
}
return keys.reduce((obj, key) => obj[key], object);
}