0

Let's say I have a string: 'first.second.last'

I also have an object:

{
    'first': {
        'second' : {
            'last': "value"
        }
    }
}

How can I access "value" using that string?

Vitaliy Isikov
  • 3,647
  • 9
  • 38
  • 46

3 Answers3

2

Something like this...

var o = {
    'first': {
        'second' : {
            'last': "value"
        }
    }
};
var s = 'first.second.last';
var val = s.split('.').reduce(function(p, c) {
    return p.hasOwnProperty(c) && p[c] || p;
}, o);

This will drill into your object and find the deepest key that matches. If instead, you want to return null for any failure to match a key, change the reduce callback to

function(p, c) {
    return p && p.hasOwnProperty(c) && p[c] || null;
}

If you need legacy support for Array.prototype.reduce, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#Polyfill

Phil
  • 157,677
  • 23
  • 242
  • 245
  • This will return unexpected results of the string doesn't match a path in the object. – Felix Kling Mar 26 '14 at 00:12
  • @FelixKling It's a top-down search. It will return the deepest value that matches (which I mentioned in the answer). I suppose it could simply return `null` but OP would need to clarify their requirements – Phil Mar 26 '14 at 00:13
1

That is not an array, it's an object. If you want to access last in that object, if there's a variable with the contents named example:

example['first']['second']['third']

If you want a dynamic setup where you're not sure of the depth try something like:

var myString = 'first.second.last'
var myObj = {
    'first': {
        'second' : {
            'last': "value"
        }
    }
}

myString.split('.').forEach(function(item) {
   myObj = myObj[item]    
})

In the end value will have your desired output. Someone might now a simple util or library that does exactly this, or a more functional way to apply this method, unfortunately nothing smarter comes to mind at this point.

bitoiu
  • 6,893
  • 5
  • 38
  • 60
0

You can access the object similar to an array used the [] notation. If you split the string into it you can go sample["first"]["second"]["third"]

Therefore, this should work I think:

var sample = {
    'first': {
        'second' : {
            'last': "value"
        }
    }
}

var str = "first.second.last";
var current = sample;
str.split('.').forEach(function(prop) {
   current = current[prop];
})
return current;