Q:

Find JSON value for a specific key in Nested JSON with unstructured keys using underscore

I have a Nested JSON object and I want to find the value of the specific key in it. let's say JSON is like this:
var data={

       name:"dsd",
       work: "abcd",
       address:{
          street:"wewe 32",
          apt: 12,
          city: "ca",
          geo:{
             lat: 23.4332,
             lng: 132.232
          },
          hobbies:["play","sing"]
       }        

 }

Now if I want to find the value of "city", then it should give me "ca", If I want to find the value of "lng" then it should return 132.232. if I want to find the value of "hobbies" it should give me [play, sing]. How can I get this? Solution using underscore or lodash will be appreciated.

A:

You can achieve this by recursively iterating over lodash#some. Check the comments below for guidance.
function getValueByKey(object, key) {
  // The resulting value of a matched key
  var result;

  // Use _.some as an iterator, to stop the iteration
  // and recursion once a match is found. Also, name 
  // the predicate function for recursion.
  _.some(object, function matchKey(value, $key) {
    if ($key === key) { // is key a match?
      result = value; // set the result
      return true; // this stops the iteration and recursion
    } else if (_.isObject(value)) { // is value an object?
      // recursively match the keys all over again
      return _.some(value, matchKey);
    }
  });

  // return matched result
  return result;
}

var data = {
  name: "dsd",
  work: "abcd",
  address: {
    street: "wewe 32",
    apt: 12,
    city: "ca",
    geo: {
      lat: 23.4332,
      lng: 132.232
    },
    hobbies: ["play", "sing"]
  }
};

function getValueByKey(object, key) {
  // The resulting value of a matched key
  var result;

  // Use _.some as an iterator, to stop the iteration
  // and recursion once a match is found. Also, name 
  // the predicate function for recursion.
  _.some(object, function matchKey(value, $key) {
    if ($key === key) { // is key a match?
      result = value; // set the result
      return true; // this stops the iteration and recursion
    } else if (_.isObject(value)) { // is value an object?
      // recursively match the keys all over again
      return _.some(value, matchKey);
    }
  });

  // return matched result
  return result;
}

console.log('hobbies:', getValueByKey(data, 'hobbies'));
console.log('geo:', getValueByKey(data, 'geo'));
console.log('lng:', getValueByKey(data, 'lng'));
.as-console-wrapper {
  min-height: 100%;
  top: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Alternative: Here's a non-recursive vanilla javascript solution:
function getValueByKey(object, key) {

  // simulate recursion by stacking
  var stack = [object];
  var current, index, value;

  // keep iterating until the stack is empty
  while (stack.length) {
    // take the head of the stack
    current = stack.pop();
    // iterate over the current object
    for (index in current) {
      // get value of the iterated object
      value = current[index];
      // is it a match?
      if (key === index) {
        return value; // return the matched value
      } 
      // value must be an object and not a null value
      // to be subject for the next stack iteration
      else if (value !== null && typeof value === 'object') {
        // add this value in the stack
        stack.unshift(value);
      }
    }
  }

}

var data = {
  name: "dsd",
  work: "abcd",
  address: {
    street: "wewe 32",
    apt: 12,
    city: "ca",
    geo: {
      lat: 23.4332,
      lng: 132.232
    },
    hobbies: ["play", "sing"]
  }
}

function getValueByKey(object, key) {

  // simulate recursion by stacking
  var stack = [object];
  var current, index, value;

  // keep iterating until the stack is empty
  while (stack.length) {
    // take the head of the stack
    current = stack.pop();
    // iterate over the current object
    for (index in current) {
      // get value of the iterated object
      value = current[index];
      // is it a match?
      if (key === index) {
        return value; // return the matched value
      } 
      // value must be an object and not a null value
      // to be subject for the next stack iteration
      else if (value !== null && typeof value === 'object') {
        // add this value in the stack
        stack.unshift(value);
      }
    }
  }

}

console.log('hobbies:', getValueByKey(data, 'hobbies'));
console.log('geo:', getValueByKey(data, 'geo'));
console.log('lng:', getValueByKey(data, 'lng'));
.as-console-wrapper { min-height: 100%; top: 0; }

