7

Trying to figure out what the easiest way to write a function keyExisits that checks and arbitrarily nested key to see if it exists in an object and is undefined, vs does not exisit.

assume this obj

var obj = {
  a: {
    b: 1,
    c: {
      d: 2,
      e: undefined
    }
  }
}

In this object the key a.c.e exists and is undefined, the key a.c.f does not exist

so

keyExists(obj, 'a.c.e') === true
keyExists(obj, 'a.c.f') === false

using lodash/underscore is ok

** UPDATE **

Lodash has works exactly like this

9
  • 2
    Disagree since this question is specific for nested keys. Answers on the linked question don't provide solutions. Commented Aug 30, 2018 at 9:31
  • 2
    This is a different question. Commented Aug 30, 2018 at 9:32
  • Anyways, check this question stackoverflow.com/questions/2631001/… Commented Aug 30, 2018 at 9:32
  • @Andrey its still a duplicate of how to check if a key exists, even if implementing recursion is needed the underlying question is the same Commented Aug 30, 2018 at 9:32
  • 1
    And lodash has _.has method lodash.com/docs/4.17.10#has Commented Aug 30, 2018 at 9:33

1 Answer 1

3

You can try following

var obj = {a: {b: 1,c: {d: 2,e: undefined}}};

function keyExists(o, key) {
  if(key.includes(".")) {
    let [k, ...rest] = key.split(".");
    return keyExists(o[k], rest.join("."));
  } else if(o) {
    return o.hasOwnProperty(key);
  }
  return false;
}

console.log(keyExists(obj, 'a.c.e') === true)
console.log(keyExists(obj, 'a.c.f') === false)

Note: The above code will not work if there are any dots in the key name or you are using [] notation.

Sign up to request clarification or add additional context in comments.

1 Comment

Performance wise, this seems quite counter productive to join the key just to split it again. It will also throw an cannot read property of undefined error if an intermediate key does not exist, i.e. keyExists(obj, 'b.c.e').

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.