Say we have this:
const keyv = 'foo.bar.star';
const v = {
foo: {
bar: {
star:'car'
}
}
};
console.log(v[keyv]); // undefined
that won't work. I am working on some metaprogramming and looking for a generic way to read a property from an object.
One way is to take a string a split it on dots/periods, like so:
const keys = String(keyv).split('.').filter(Boolean);
const result = keys.reduce(function (a, b) {
return a[b] || '';
}, obj);
console.log(result);
the only problem with that solution is if a property name has a dot/period in it, and then we are screwed.
So I was trying to use eval()
instead to run the property look up, like so:
const expression = `obj[keyv]`;
let value = eval(expression);
if (value && typeof value === 'object') {
console.log(JSON.stringify(value));
}
else {
console.log(value);
}
but this will only work for a single property, as you can see. I need to be able to read as many properties as is relevant.