1
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Any reason why target is formatted in that way? \$\endgroup\$ – Joseph May 24 '16 at 15:21
  • \$\begingroup\$ @DavidFoerster @josephthedreamer I can change the Target, is it best to use reduce there to get the location returned (just learned that function) or should I use a different approach? \$\endgroup\$ – Randy May 24 '16 at 16:03
3
\$\begingroup\$

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

|improve this answer|||||
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.