The other solutions will most likely fail when you try to access a nested object
, that is, a more complex object that has another object inside, and we want to access a pripiedad that is well inside, well, I did a small utilitarian function that can help solve this problem:
function getProps(obj, path) {
var arr = path.split('.');
var parent = obj;
var name = arr[0];
arr.slice(1).forEach((fieldName) => {
parent[name] = parent[name] || {};
parent = parent[name];
name = fieldName;
});
return parent[name];
}
var obj = {
bar: {
foo: 3,
hello: {
there: {
foo: 3
}
}
}
}
console.log(getProps(obj, 'bar.foo'));
console.log(getProps(obj, 'bar.hello.there'));
Update
I leave the complete example of how I use it, which suits it for the answer, it is more complete because you can also modify the json, and create the parent fields as necessary:
export function resolvePath(obj: any, path: string) {
const arr = path.split(".");
let parent = obj;
let name = arr[0];
arr.slice(1).forEach((fieldName) => {
parent[name] = parent[name] || {};
parent = parent[name];
name = fieldName;
});
return {
get(): any {
return parent[name];
},
set(value: any) {
parent[name] = value;
},
delete() {
delete parent[name];
},
ref() {
return [parent, name];
},
};
}