[英]Check if key exists in nested object
Object.keys
, that may not work here. Object.keys
之前,这可能在这里不起作用。 Please read on before voting to close or commenting. Consider the following object and the value being passed in: 考虑以下对象和传入的值:
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
. 但是,目的是要传递的键可能存在于此对象的某些位置,如果要这样做,我想返回
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." 我在堆栈和Web上找到的所有内容都是“通过值查找密钥”。 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.
我看过lodash和下划线以及一堆堆栈问题,但是什么也没发现。
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
. 如果我传入了
other_cause_of_death
我应该回到true
。
Thoughts? 思考?
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.
同样的规则仍然适用。
You can use a recursive approach (DFS) to find the object next to your key. 您可以使用递归方法(DFS)在密钥旁边找到对象。 If a non-null object is returned, you can get its
hide
value: 如果返回非空对象,则可以获取其
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'));
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. 它遵循Immutable.js方法从不可变地图获取内容的工作方式。
This will return undefined
for an invalid key path. 对于无效的密钥路径,这将返回
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.