如果我有对象的引用:
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);
}
但我想知道是否有更好的方法。
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))
这个功能怎么样?它不需要单独列出每个嵌套属性,而是保持“dot”语法(尽管是字符串),使其更具可读性。如果未找到属性,则返回undefined或指定的默认值,如果找到,则返回属性的值。
val(obj, element, default_value)
// Recursively checks whether a property of an object exists. Supports multiple-level nested properties separated with '.' characters.
// obj = the object to test
// element = (string or array) the name of the element to test for. To test for a multi-level nested property, separate properties with '.' characters or pass as array)
// default_value = optional default value to return if the item is not found. Returns undefined if no default_value is specified.
// Returns the element if it exists, or undefined or optional default_value if not found.
// Examples: val(obj1, 'prop1.subprop1.subsubprop2');
// val(obj2, 'p.r.o.p', 'default_value');
{
// If no element is being requested, return obj. (ends recursion - exists)
if (!element || element.length == 0) { return obj; }
// if the element isn't an object, then it can't have properties. (ends recursion - does not exist)
if (typeof obj != 'object') { return default_value; }
// Convert element to array.
if (typeof element == 'string') { element = element.split('.') }; // Split on dot (.)
// Recurse into the list of nested properties:
let first = element.shift();
return val(obj[first], element, default_value);
}
下面是我的看法-这些解决方案中的大多数都忽略了嵌套数组的情况,如:
obj = {
"l1":"something",
"l2":[{k:0},{k:1}],
"l3":{
"subL":"hello"
}
}
我可能想检查obj.l2[0].k
使用下面的函数,您可以执行深度测试('l2[0].k',obj)
如果对象存在,函数将返回true,否则返回false
函数deeptest(keyPath,testObj){变量obj;keyPath=keyPath.split('.')var cKey=keyPath.shift();函数get(pObj,pKey){var bracketStart,bracketEnd,o;bracketStart=pKey.indexOf(“[”);if(bracketStart>-1){//检查嵌套数组bracketEnd=pKey.indexOf(“]”);var arrIndex=pKey.substr(bracketStart+1,bracketEnd-bracketStart-1);pKey=pKey.substr(0,括号开始);var n=pObj[pKey];o=n?n[arrIndex]:未定义;}其他{o=pObj[pKey];}返回o;}obj=获取(testObj,cKey);while(obj&&keyPath.length){obj=get(obj,keyPath.shift());}返回typeof(obj)!=='未定义';}变量obj={“l1”:“级别1”,“arr1”:[{“k”:0},{“k”:1},{“k”:2}],“子”:{“a”:“字母a”,“b”:“字母b”}};console.log(“l1:”+深度测试(“l1”,obj));console.log(“arr1[0]:”+深度测试(“arr1[0]”,obj));console.log(“arr1[1].k:”+深度测试(“arr1].k”,obj));console.log(“arr1[1].j:”+深度测试(“arr1].j”,obj));console.log(“arr1[3]:”+深度测试(“arr1[3]”,obj));console.log(“arr2:”+深度测试(“arr2”,obj));