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?
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?
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
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.
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;