2

I m trying to access an object property through a string.

What I m trying to do is :

const data = {
    key: {
        subKey: 'value'
    }
};

const theString = 'key.subKey';

function accessPropFromString(obj, stringCall) {
    // I don't know what to put on here
}

console.log(accessPropFromString(data, theString)) // prints 'value'

I absolutely don't know how to make that happen...

How can I do this kind of stuff with JavaScript ?

mfrachet
  • 8,772
  • 17
  • 55
  • 110

3 Answers3

3

You could split the path and reduce the object.

const getValue = (object, path) => path.split('.').reduce((o, k) => (o || {})[k], object),
      data = { key: { subKey: 'value' } },
      theString = 'key.subKey';

console.log(getValue(data, theString));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • I think this is as good as it's likely to get given that we're starting with a single string. There's an API problem in that it won't handle properties whose names contain a `'.'`, but that's intrinsic to the question. – Scott Sauyet Feb 25 '17 at 18:02
  • @ScottSauyet, right, an array as parameter would be better for strings with dots. – Nina Scholz Feb 25 '17 at 18:04
  • Yes, and when I [dealt with this](http://ramdajs.com/docs/#path) in my library, I reluctantly went with an array. I like the simplicity of such strings, but there were too many counterexamples. – Scott Sauyet Feb 25 '17 at 18:06
1

This should work. Assuming, you have fixed format.

function accessPropFromString(obj, stringCall) {
   var splitter =stringCall.split(".");
   return data[splitter[0]][splitter[1]];
}

Demo

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

See comments inline:

const data = {
    key: {
        subKey: 'value'
    }
};

const theString = 'key.subKey';

function accessPropFromString(obj, stringCall) {
    // Split the string into individual parts
    var parts = stringCall.split(".");
    
    // You can use strings to lookup properties on objects
    // if you use bracket notation, like this;
    // parts["key"]["subKey"]
    // So, parts[0] will be "key" and parts[1] will be "subKey"
    return obj[parts[0]][parts[1]];
}

console.log(accessPropFromString(data, theString)) // prints 'value'
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71