繁体   English   中英

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

[英]Check if key exists in nested object

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

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

在此处输入图片说明

如您所见,我有一个密钥,该密钥在此对象中不存在。 但是,目的是要传递的键可能存在于此对象的某些位置,如果要这样做,我想返回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
      }
    }
  }
};

这是对象的简化版本。 同样的规则仍然适用。

您可以使用递归方法(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')); 

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

它遵循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']
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM