lodash get method equivalent in javascript I wanted to build similar to lodash get method. Where you put the object and key name to get value if exist. I have done this but just wanted to have more better approach. Here is what has been done so bar.

var x = {
  d: 'new vale',
  a: {
    b: {
      c: {
        e: 'value'
      }
    }
  }

}

function getVal(obj, key) {
  var keys = obj[key];
  if (!keys) {
    for (var i in obj) {
      if (Object.prototype.toString.call(obj[i]) === '[object Object]') {
        return getVal(obj[i], key)
      }

    }
  } else {
    return obj[key]
  }

}

console.log(getVal(x, 'c'))
You can try the following script as alternate approch which:


Get a nested property of a complex object at any level of depth without using recursion.


This script uses replacer optional function for JSON.stringify(), basically it takes a JavaScript value (your initial object) and convert to a JSON string, and it uses that string to search within your array. The script works without any recursions, with any number of nested properties for your objects. The order of your property is important in this script, as the conversion to string take it in consideration.

Cavet: Date object is returned stringified.



let data = {
  d: 'new vale',
  a: {
    b: {
      c: {
        e: 'value'
      }
    }
  }
};

let getPropertyRecursive = function(data, name) {
  let result = {
    isFound: false,
    value: null
  };
  JSON.stringify(data, function(k, v) {
    if (k === name) {
      result.isFound = true;
      result.value = v;
      return undefined;
    } else {
      return v;
    }
  });
  return result;
};

let result1 = getPropertyRecursive(data, 'e');
let result2 = getPropertyRecursive(data, 'a');
console.log(result1);
console.log('-----');
console.log(result2 );