在javascript中,有没有一种方法可以在不检查每一层的情况下,对对象的属性编写几层深的条件



我有一个对象:

let someObject = {
someKey: {
otherKey: {
key3: {
youGetThePoint: null
}
}
}
};

如果我写:

if (someObject.someKey.otherKey.key3.youGetThePoint) {
doStuff();
}

并且一些方法从CCD_ 2中的对象中移除CCD_。

有没有一种方法可以在不将几个&&链接在一起或嵌套几个条件来检查每一层的情况下编写这个条件?即避免:

if (someObject && someObject.someKey && some...

let someObject = {
someKey: {
otherKey: {
key3: {
youGetThePoint: null
}
}
}
};
function objNestedCheck(someObject, someKey, otherKey, key3, youGetThePoint) {
var args = Array.prototype.slice.call(arguments, 1);
for (var i = 0; i < args.length; i++) {
if (!someObject|| !someObject.hasOwnProperty(args[i])) {
return false;
}
someObject= someObject[args[i]];
}
return true;
}
objNestedCheck(someObject , 'someKey', 'otherKey', 'key3', 'youGetThePoint');
if (objNestedCheck(someObject , 'someKey', 'otherKey', 'key3', 'youGetThePoint')) {
// you can do your stuff here 
doStuff();
}

使用ES6功能和递归

function checkNested(someObject , someKey,  ...rest) {
if (someObject === undefined) return false
if (rest.length == 0 && someObject .hasOwnProperty(someKey)) return true
return checkNested(someObject [level], ...rest)
}
if (checkNested(someObject , someKey,  ...rest)) {
// you can do your stuff here 
doStuff();
}

相关内容

最新更新