Skip to content Skip to sidebar Skip to footer

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\' &&

Solution 1:

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

Solution 2:

You can split the key on the . before accessing them on the object

var keys = argv[2].split('.');
var result = obj;
keys.forEach(function(key){
    result = result[key]
});
return result;

Post a Comment for "Pulling A Deep Property From A Json Without Using Lodash Get"