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 ?

4
  • 2
    You're not new here. You know the routine. What have you tried so far? Commented Feb 25, 2017 at 17:53
  • Use template literals instead: const theString = `${key.subKey}`; Commented Feb 25, 2017 at 17:53
  • @trincot: what if the value in question is not a string? Commented Feb 25, 2017 at 17:56
  • @ScottSauyet, then use a tag function: ((_, val) => val)`${data.key.subKey}`; Commented Feb 25, 2017 at 18:04

3 Answers 3

4

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));

Sign up to request clarification or add additional context in comments.

3 Comments

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.
@ScottSauyet, right, an array as parameter would be better for strings with dots.
Yes, and when I dealt with this in my library, I reluctantly went with an array. I like the simplicity of such strings, but there were too many counterexamples.
1

This should work. Assuming, you have fixed format.

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

Demo

2 Comments

what do you do with another level?
Yes, not very generic.
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'

2 Comments

What happens with additional levels?
@ScottSauyet You're right, it doesn't handle that. I was really just demonstrating how bracket-notation should be used to access properties with strings. By the way, how are you? ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.