Federico Lenzi
Federico Lenzi

Reputation: 1612

nodejs json dynamic property

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

Upvotes: 0

Views: 1932

Answers (1)

meetamit
meetamit

Reputation: 25157

var current = result,
    path = 'asd.qwe';

path.split('.').forEach(function(token) {
  current = current && current[token];
});

console.log(current);// Would be undefined if path didn't match anything in "result" var

EDIT

The purpose of current && ... is so that if current is undefined (due to an invalid path) the script won't try to evaluate undefined["something"] which would throw an error. However, I've just realized the if current happens to be falsy (i.e. false or zero or an empty string) this would fail to look up the property in token. So probably the check should be current != null.

ANOTHER EDIT

Here's a much better, idiomatic way to do it in one line, using the Array.reduce() method:

path.split('.').reduce(
  function(memo, token) {
    return memo != null && memo[token];
  },
  resultJson
);

This is also better because it doesn't require ANY vars

Upvotes: 3

Related Questions