javascript 检查嵌套对象键的存在

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 检查嵌套对象键的存在相关的知识,希望对你有一定的参考价值。

let obj = {
  levelOne: {
    levelTwo: {
      levelThree: {
        asd: 'kek'
      }
    }
  }
}

// Source: https://stackoverflow.com/questions/2631001/test-for-existence-of-nested-javascript-object-key
// Benchmarked with: http://jsben.ch/7aJgK
// Use whathever you want. 
// Existence checking

// Object Wrap (by Oliver Steele) – 34 % – fastest
var r1 = ((((obj || {}).levelOne || {}).levelTwo || {}).levelThree || {}).asd; // exists returns: kek
var r2 = ((((obj || {}).levelOne || {}).levelTwo || {}).levelThree || {}).notFound; // not exists returns: undefined

// Standard solution – 45%
var r1 = obj.levelOne && obj.levelOne.levelTwo && obj.levelOne.levelTwo.levelThree && obj.levelOne.levelTwo.levelThree.asd // exists returns: kek
var r1 = obj.levelOne && obj.levelOne.levelTwo && obj.levelOne.levelTwo.levelThree && obj.levelOne.levelTwo.levelThree.notFound // not exists returns: undefined

// checkNested – 50%

function checkNested(obj) {
  for (var i = 1; i < arguments.length; i++) {
    if (!obj.hasOwnProperty(arguments[i])) {
      return false;
    }
    obj = obj[arguments[i]];
  }
  return true;
}

// get_if_exist – 52%
function get_if_exist(str) {
    try { return eval(str) }
    catch(e) { return undefined }
}

// validChain – 54%
function validChain( object, ...keys ) {
    return keys.reduce( ( a, b ) => ( a || { } )[ b ], object ) !== undefined;
}

// objHasKeys – 63%
function objHasKeys(obj, keys) {
  var next = keys.shift();
  return obj[next] && (! keys.length || objHasKeys(obj[next], keys));
}

// nestedPropertyExists – 69%
function nestedPropertyExists(obj, props) {
    var prop = props.shift();
    return prop === undefined ? true : obj.hasOwnProperty(prop) ? nestedPropertyExists(obj[prop], props) : false;
}

// Lodash get _.get – 72%

// deeptest – 86%
function deeptest(target, s){
    s= s.split('.')
    var obj= target[s.shift()];
    while(obj && s.length) obj= obj[s.shift()];
    return obj;
}

// sad clowns – 100% – slowest
var o = function(obj) { return obj || {} };

var r1 = o(o(o(o(test).level1).level2).level3);
var r2 = o(o(o(o(test).level1).level2).foo);

以上是关于javascript 检查嵌套对象键的存在的主要内容,如果未能解决你的问题,请参考以下文章

测试嵌套 JavaScript 对象键是不是存在

测试嵌套 JavaScript 对象键是不是存在

按对象键的Firestore查询

JavaScript:将具有父键的对象数组转换为父/子树(包括没有父的对象)

JavaScript,检查嵌套对象属性是不是为空/未定义的优雅方法[重复]

检查/访问 QML 中动态创建的对象