function getValueByKeyPath(obj, path) {
return String(path)
.split(/\.|\[['"]?([^'"\]]*)['"]?\]/)
.filter(elm => !!elm)
.reduce((value, key) => value?.[key], Object(obj))
}
const sampleDataA = {
foo: {
value: 'foo',
bar: {
value: 'bar',
baz: {
value: 'baz',
},
},
},
};
const sampleDataB = {
foo: {
bar: [{
baz: {
value: 'baz',
biz: {
value: 'biz',
},
}
}, {
buzz: {
value: 'buzz',
booz: {
value: 'booz',
},
}
}],
},
};
console.log(
"getValueByKeyPath(sampleDataA, 'foo.bar.baz.value') ...",
getValueByKeyPath(sampleDataA, 'foo.bar.baz.value')
);
console.log(
"getValueByKeyPath(sampleDataA, 'foo.bar[\"baz\"].value') ...",
getValueByKeyPath(sampleDataA, 'foo.bar["baz"].value')
);
console.log(
"getValueByKeyPath(sampleDataB, 'foo.bar[1][\"buzz\"].booz') ...",
getValueByKeyPath(sampleDataB, 'foo.bar[1]["buzz"].booz')
);
console.log(
"fail safe ... getValueByKeyPath(sampleDataB, 'foo.bar[2].buzz.booz') ...",
getValueByKeyPath(sampleDataB, 'foo.bar[2].buzz.booz')
);
.as-console-wrapper { min-height: 100%!important; top: 0; }