I want to make a simple app that receives a json object, and a path. The result is the value of that path, for example:
node {"asd":{"qwe":"123", "ert":"465"}} asd.qwe
should return me: 123
I’m using this:
var result = JSON.parse(jsonToBeParsed);
console.log(result["asd"]["qwe"]);
But I want to be able of getting the values dinamically with a string.
Is there a way to do something like this? :
var result = JSON.parse(jsonToBeParsed);
var path = "asd.qwe" //or whatever
console.log(result[path]);
EDIT
The purpose of
current && ...is so that ifcurrentis undefined (due to an invalid path) the script won’t try to evaluateundefined["something"]which would throw an error. However, I’ve just realized the ifcurrenthappens to be falsy (i.e.falseor zero or an empty string) this would fail to look up the property intoken. So probably the check should becurrent != null.ANOTHER EDIT
Here’s a much better, idiomatic way to do it in one line, using the Array.reduce() method:
This is also better because it doesn’t require ANY
vars