检查键是否在嵌套对象中存在

时间:2019-06-04 21:52:52

标签: javascript

在任何人说Object.keys之前,这可能在这里无效。请先投票阅读,然后再投票结束或发表评论。

考虑以下对象和传入的值:

enter image description here

如您所见,我有一个密钥,该密钥在此对象中不存在。但是,这样做的目的是要传递的键可能存在于此对象的某些位置,如果要返回,我想返回hide的值。

因此,示例如下:

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

我在堆栈和Web上找到的所有内容都是“通过值查找密钥”。我没有价值,我只有一个潜在的关键。我看过 lodash 下划线以及一堆堆栈问题,但一无所获。

任何想法或帮助将不胜感激。对象嵌套应该无关紧要。如果我通过了other_cause_of_death,我应该找回true

有想法吗?

编辑:

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

这里是对象的简化版本。相同的规则仍应适用。

2 个答案:

答案 0 :(得分:1)

您可以使用递归方法(DFS)在密钥旁边找到对象。如果返回非空对象,则可以获取其hide值:

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

答案 1 :(得分:0)

由于您正在使用某些结构化数据,因此这可能是一种有效的方法:

它遵循Immutable.js方法,以了解如何从不可变地图获取内容。

这将返回undefined的无效密钥路径。

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']
);
相关问题