0

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.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • 2
    Why not have `keyv` be an array instead of a string? – CertainPerformance Jun 11 '18 at 03:40
  • Because at the command line, the user would have to put in the list of properties, but I guess that could work – Alexander Mills Jun 11 '18 at 03:42
  • 1
    [lodash.get](https://lodash.com/docs#get) provides this exact functionality. If you are interested in their implementation check out their [source code](https://github.com/lodash/lodash/blob/4.17.10/lodash.js#L13125). I would avoid using `eval` unless you have a very good reason to use it, it can be risky to use. – morsecodist Jun 11 '18 at 03:50
  • this library do that https://github.com/braceslab/a-toolbox#objectflatobj – Simone Sanfratello Jun 11 '18 at 04:04

0 Answers0