Javascript: Access Nested Values In Json Data Using Dynamic Variable Names
Solution 1:
Don't use eval
unless absolutely necessary. :) At least in this case, there are better ways to do it -- you can split the nested name into individual parts and iterate over them:
data.get = function(p) {
var obj = this;
p = p.split('.');
for (var i = 0, len = p.length; i < len - 1; i++)
obj = obj[p[i]];
return obj[p[len - 1]];
};
data.set = function(p, value) {
var obj = this;
p = p.split('.');
for (var i = 0, len = p.length; i < len - 1; i++)
obj = obj[p[i]];
obj[p[len - 1]] = value;
};
Solution 2:
You can just nest the brackets:
var a = 'name', b = 'heading';
data[a][b]; // = `Name`
Solution 3:
Perhaps a function that takes in the path to the property you're interested in and breaks it up into tokens representing properties. Something like this (this is very rough, of course):
data.get = function(path) {
var tokens = path.split('.'), val = this[tokens[0]];
if (tokens.length < 2) returnval;
for(var i = 1; i < tokens.length; i++) {
val = val[tokens[i]];
}
returnval;
}
example:
var f = 'one.two';
vardata = { one: {two:'hello'}};
data.get = /* same as above */;
varval = data.get(f);
Solution 4:
A clean way to access/set nested values is using reduce
in ES6:
const x = ['a', 'b', 'c'], o = {a: {b: {c: 'tigerking'}}}
// Get value: "tigerking"console.log(x.reduce((a, b) => a[b], o))
// Set value:
x.slice(0, x.length-1).reduce((a, b) => a[b], o)[x[x.length-1]] = 'blossom'console.log(o) // {a: {b: {c: 'blossom'}}}
So, you can first convert your variable 'profile.age'
to an array using 'profile.age'.split('.')
, then use the approach above.
Solution 5:
This uses the jquery.each() function to traverse down a json tree using a string variable that may or may not contain one or more "."'s. You could alternatively pass in an array and omit the .split();
pathString = something like "person.name"
jsonObj = something like {"person" : {"name":"valerie"}}.
functiongetGrandchild(jsonObj, pathString){
var pathArray = pathString.split(".");
var grandchild = jsonObj;
$.each(pathArray, function(i, item){
grandchild = grandchild[item];
});
return grandchild;
};
returns "valerie"
Post a Comment for "Javascript: Access Nested Values In Json Data Using Dynamic Variable Names"