devwannabe devwannabe - 6 months ago 13
Node.js Question

Pulling a deep property from a json without using lodash get

So we've got a sample json

{
"name": "app",
"version": "0.1.0",
"description": "Sample description",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "some git url"
},
"keywords": [
"node"
],
"author": "Anonymous",
"license": "ISC"
}


and here is our node.js script

var obj = require('./package.json');
console.log(obj[process.argv[2]]);


When I execute
node getval.js version
, it works. However, when I execute
node getval.js repository.url
, I get undefined.

When I change the code to the one below, it works. However, I don't want to hardcode the key values

console.log(obj['repository']['url']);

Answer

Given an object obj and a "repository.url" key, you can get the deep value with

var val = key.split(".").reduce((o,k)=>o[k],obj);

Demonstration:

var obj = {
  "name": "app",
  "version": "0.1.0",
  "description": "Sample description",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "some git url"
  },
  "keywords": [
    "node"
  ],
  "author": "Anonymous",
  "license": "ISC"
};

var key = "repository.url";

var val = key.split(".").reduce((o,k)=>o[k],obj);

document.write("result: \"" + val + "\"");

Now, imagine you want something which doesn't throw an exception when some properties are missing, for example "repository.language.version", then you could do

var val = key.split(".").reduce((o={},k)=>o[k],obj);