3
\$\begingroup\$

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'))
\$\endgroup\$
  • \$\begingroup\$ Related: Accessing nested JavaScript objects with string key \$\endgroup\$ – Jonathan Lonowski Jun 9 '17 at 6:11
  • \$\begingroup\$ That's a really strange way to test if something is an object. Why not just if (typeof obj[i] == "object")? \$\endgroup\$ – Barmar Jun 9 '17 at 22:28
  • \$\begingroup\$ @Barmar because typeof [] is also equal to "object" \$\endgroup\$ – Carlos Jun 13 '17 at 6:55
2
\$\begingroup\$

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

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ I just checked its performance in jsperf. It quite slow in compare to solution given in question. jsperf.com/find-nested-key \$\endgroup\$ – Carlos Jun 13 '17 at 7:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.