TheWebs
TheWebs

Reputation: 12923

Check if key exists in nested object

Before any one sais Object.keys, that may not work here. Please read on before voting to close or commenting.

Consider the following object and the value being passed in:

enter image description here

As you can see I have a key, which doesn't exist in this object. But the intention is that the key being passed in might exist some where in this object and if it does I want to return the value of the hide.

So an example would be something like:

// Pseudo code, `object` is the object in the screen shot.
if (object.hasKey('date_of_visit')) {
  return object.find('date_of_visit').hide
}

Everything I have ever found on stack and the webs is "find the key by the value." I do not have the value, I just have a potential key. I have looked at lodash and underscore and a bunch of stack questions but have found nothing.

Any ideas or help would be greatly appreciated. The object nesting should not matter. If I passed in other_cause_of_death I should get back true.

Thoughts?

Edit:

const object = {
  status: {
    cause_of_death: {
      hide: true,
      other_cause_of_death: {
        hide: true
      }
    }
  }
};

Heres a simplified version of the object. Same rules should still apply.

Upvotes: 0

Views: 339

Answers (2)

Henrik Andersson
Henrik Andersson

Reputation: 47172

Since you're working with some structured data this could be a valid approach:

It follows the Immutable.js approach to how getting stuff from immutable maps works.

This will return undefined for an invalid key path.

function getIn(obj, keyPath) {
  return keyPath.reduce((prev, curr) => {
    return Object.keys(prev).length ? prev[curr] : obj[curr];
  }, {});
}

const res = getIn(
    data, ['status', 'cause_of_death', 'other_cause_of_death', 'hide']
);

Upvotes: 0

slider
slider

Reputation: 12990

You can use a recursive approach (DFS) to find the object next to your key. If a non-null object is returned, you can get its hide value:

const data = {
  status: {
    cause_of_death: {
      hide: true,
      other_cause_of_death: {
        hide: true
      }
    },
    date_of_birth: {
      hide: true
    }
  }
};

function findKey(obj, key) {
  if (typeof obj !== 'object') return null;
  if (key in obj) return obj[key];
  for (var k in obj) {
    var found = findKey(obj[k], key);
    if (found) return found;
  }
  return null;
}

console.log(findKey(data, 'date_of_birth'));
console.log(findKey(data, 'cause_of_death'));
console.log(findKey(data, 'other_cause_of_death'));
console.log(findKey(data, 'hello'));

Upvotes: 1

Related Questions