正在检查对象javascript中是否存在嵌套属性

Checking existence of nested property in an object javascript

本文关键字:是否 存在 嵌套 属性 javascript 检查 对象      更新时间:2023-09-26

我已经复习了一些类似问题的答案,但我想以不同的方式提问。

假设我们有一个字符串,类似于"级别1.级别2.级别3……",表示名为Obj的对象中的嵌套属性。

关键是,我们可能不知道这个字符串中有多少嵌套属性。例如,它可以是";level1、level2";或";级别1.级别2.级别3.级别4";。

现在,我想写一个函数,给定Obj和属性字符串作为输入,简单地告诉我们对象中是否存在这样的嵌套属性(假设输出为true或false)。


更新:感谢@Silvinus,我找到了一个小修改的解决方案:

        private checkNestedProperty(obj, props) {
        var splitted = props.split('.');
        var temp = obj;
        for (var index in splitted) {
            if (temp[splitted[index]] === 'undefined' || !temp[splitted[index]]) return false;
            temp = temp[splitted[index]];
        }
        return true;
    }

您可以通过迭代键并检查它是否在给定对象中来使用它的Array#every()thisArg

var fn = function (o, props) {
    return props.split('.').every(k => k in o && (o = o[k], true));
}
console.log(fn({}, "toto.tata"));                                   // false
console.log(fn({ toto: { tata: 17 } }, "toto.tata"));               // true
console.log(fn({ toto: { tata: { tutu: 17 } } }, "toto.foo.tata")); // false
console.log(fn({ toto: { tata: false } }, "toto.tata")); // true

您可以使用以下函数来探索您的Obj:

var fn = function(obj, props) {
        var splited = props.split('.');
        var temp = obj;
        for(var index in splited) {
            if(typeof temp[splited[index]] === 'undefined') return false;
            temp = temp[splited[index]]
        }
           return true
        }
var result = fn({ }, "toto.tata");
console.log(result); // false
var result = fn({ toto: { tata: 17 } }, "toto.tata");
console.log(result); // true
var result = fn({ toto: { tata: { tutu: 17 } } }, "toto.foo.tata");
console.log(result); // false

此函数允许探索Obj的嵌套属性,该属性取决于参数中传递的道具

这个答案为您的问题提供了基本答案。但它需要调整以处理未定义的情况:

function isDefined(obj, path) {
  function index(obj, i) { 
    return obj && typeof obj === 'object' ? obj[i] : undefined; 
  }
  return path.split(".").reduce(index, obj) !== undefined;
}

基于@Silvinus给出的解决方案,如果您处理嵌套对象中的数组,这里有一个解决方案(通常是数据库查询的结果):

checkNested = function(obj, props) {
    var splited = props.split('.');
    var temp = obj;
    for(var index in splited) {
      var regExp = /'[([^)]+)']/;
      var matches = regExp.exec(splited[index])
      if(matches) {
        splited[index] = splited[index].replace(matches[0], '');
      }
      if(matches) {
        if(matches && typeof temp[splited[index]][matches[1]] === 'undefined') return false;
            temp = temp[splited[index]][matches[1]];
      }
      else {
            if(!matches && typeof temp[splited[index]] === 'undefined') return false;
                temp = temp[splited[index]]
      }
    }
    return true
}
obj = {ok: {ao: [{},{ok: { aa: ''}}]}}
console.log(checkNested(obj, 'ok.ao[1].ok.aa')) // ==> true
console.log(checkNested(obj, 'ok.ao[0].ok.aa')) // ==> false