如果我有对象的引用:
var test = {};
可能(但不是立即)具有嵌套对象,例如:
{level1: {level2: {level3: "level3"}}};
检查深度嵌套对象中是否存在属性的最佳方法是什么?
警报(测试级别1);生成未定义,但警告(test.level1.level2.level3);失败。
我目前正在做这样的事情:
if(test.level1 && test.level1.level2 && test.level1.level2.level3) {
alert(test.level1.level2.level3);
}
但我想知道是否有更好的方法。
一个简短的ES5版本@CMS的优秀答案:
// Check the obj has the keys in the order mentioned. Used for checking JSON results.
var checkObjHasKeys = function(obj, keys) {
var success = true;
keys.forEach( function(key) {
if ( ! obj.hasOwnProperty(key)) {
success = false;
}
obj = obj[key];
})
return success;
}
通过类似测试:
var test = { level1:{level2:{level3:'result'}}};
utils.checkObjHasKeys(test, ['level1', 'level2', 'level3']); // true
utils.checkObjHasKeys(test, ['level1', 'level2', 'foo']); // false
这有一个小模式,但在某些时候可能会让人不知所措。我建议您一次使用两个或三个嵌套。
if (!(foo.bar || {}).weep) return;
// Return if there isn't a 'foo.bar' or 'foo.bar.weep'.
正如我可能忘记提到的,你也可以进一步扩展。下面的示例显示了对嵌套foo.bar.weep.woop的检查,如果没有可用的,则返回。
if (!((foo.bar || {}).weep || {}).woop) return;
// So, return if there isn't a 'foo.bar', 'foo.bar.weep', or 'foo.bar.weep.woop'.
// More than this would be overwhelming.
function propsExists(arg) {
try {
const result = arg()
if (typeof result !== 'undefined') {
return true
}
return false
} catch (e) {
return false;
}
}
此函数还将测试0,null。如果他们在场,它也将返回真实。
例子:
函数propsExists(arg){尝试{常量结果=arg()if(结果类型!==“undefined”){返回true}return false}捕获(e){return false;}}让obj={测试:{a: 空,b: 0,c: 未定义,d: 4中,e: “嘿”,f: ()=>{},g: 5.4中,h: 假,i: 真的,j: {},k: [],我:{a: 1中,}}};console.log('obj.test.a',propsExists(()=>obj.test/a))console.log('obj.test.b',propsExists(()=>obj.test.b))console.log('obj.test.c',propsExists(()=>obj.test.c))console.log('obj.test.d',propsExists(()=>obj.test-d))console.log('obj.test.e',propsExists(()=>obj.test.ex))console.log('obj.test.f',propsExists(()=>obj.test-f))console.log('obj.test.g',propsExists(()=>obj.test/g))console.log('obj.test.h',propsExists(()=>obj.test.h))console.log('obj.test.i',propsExists(()=>obj.test-i))console.log('obj.test.j',propsExists(()=>obj.test.j))console.log('obj.test.k',propsExists(()=>obj.test.k))console.log('obj.test.l',propsExists(()=>obj.test/l))
还有一个非常紧凑的:
function ifSet(object, path) {
return path.split('.').reduce((obj, part) => obj && obj[part], object)
}
打电话:
let a = {b:{c:{d:{e:'found!'}}}}
ifSet(a, 'b.c.d.e') == 'found!'
ifSet(a, 'a.a.a.a.a.a') == undefined
它的性能不会很好,因为它拆分了一个字符串(但增加了调用的可读性),并遍历所有内容,即使已经很明显找不到任何内容(但提高了函数本身的可读性。
至少比get快http://jsben.ch/aAtmc