I have JSON with references to other parts in that JSON file.
// the function I would like to be reviewed
function referenceToObject(json, reference){
return (new Function(
'json', 'return json' + reference
))(json);
}
// json
var example = {
"target": "['first']['second']",
"first": {
second: 'hi'
}
};
// execution
console.log(referenceToObject(example, example.target));
That function basically executes like this:
return json['one']['two'];
Is there a better way to extract the JSON
reference? I'm able to change every bit of this code, as well as the JSON
because we are reworking the front- and the backend. So, if you have ideas to improve the JSON
instead of the Javascript
that would also be great.
1 Answer 1
Assuming that you control over the value of the target
attribute, I suggest to store the reference chain as a list of attribute names. Then you can easily resolve the reference without having to resort to eval
-like meta-programming. A reduction would be ideal like you mentioned.
function referenceToObject(json, target)
{
if (target === undefined)
target = json.target;
return target.reduce(referenceToObject.reductor, json);
}
referenceToObject.reductor = function(obj, attrib)
{
return obj[attrib];
};
var example = {
"target": ['first', 'second'],
"first": {
second: 'hi'
}
};
console.log(referenceToObject(example));
Explore related questions
See similar questions with these tags.
target
is formatted in that way? \$\endgroup\$reduce
there to get the location returned (just learned that function) or should I use a different approach? \$\endgroup\$