简体   繁体   English

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

[英]Checking existence of nested property in an object javascript

I have already reviewed some of the answers to such question, however, I want to ask my question differently. 我已经回顾了这个问题的一些答案,但是,我想以不同的方式提出我的问题。

Lets say we have a string like : "level1.level2.level3. ..." that indicates a nested property in an object called Obj . 假设我们有一个字符串: “level1.level2.level3 ....” ,表示名为Obj的对象中的嵌套属性。

The point is that we may not know that how many nested properties exist in this string. 关键是我们可能不知道该字符串中存在多少嵌套属性。 For instance, it may be "level1.level2" or "level1.level2.level3.level4". 例如,它可以是“level1.level2”或“level1.level2.level3.level4”。

Now, I want a function that given the Obj and the string of properties as input, simply tell us that if such a nested property exist in the object or not (lets say true or false as output). 现在,我想要一个给出Obj和属性字符串作为输入的函数,只需告诉我们,如果对象中存在这样的嵌套属性(假设为true或false作为输出)。


Update: Thanks to @Silvinus, I found the solution with a minor modification: 更新:感谢@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;
    }

You can explore your Obj with this function : 您可以使用此功能探索您的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

This function allow to explore nested property of Obj that depends of props passed in parameter 此函数允许探索Obj的嵌套属性,该属性取决于参数中传递的props

You could use Array#every() and thisArg of it, by iterating the keys and checking if it is in the given object. 您可以通过迭代键并检查它是否在给定对象中来使用Array#every()thisArg

 var fn = function (o, props) { return props.split('.').every(k => k in o && (o = o[k])); } 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 

This answer provides the basic answer to your question. 这个答案提供了你的问题的基本答案。 But it needs to be tweaked to handle the undefined case: 但需要调整它来处理未定义的情况:

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

  return path.split(".").reduce(index, obj) !== undefined;
}

Based on the solution given by @Silvinus here is a solution if you deal with array inside nested objects (as it is often the case in results from databases queries) : 根据@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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Javascript-在检查对象属性存在时避免异步竞争条件 - Javascript - avoiding asynchronous race condition when checking object property existence 检查数组中具有特定属性的对象的存在 - Checking the existence of an object with a certain property within an array 测试是否存在嵌套的 JavaScript object 密钥 - Test for existence of nested JavaScript object key 检查嵌套的javascript对象数组中是否存在元素 - Check existence of an element in a nested javascript object array 检查JavaScript中是否存在属性 - Checking existence of properties in JavaScript 在JavaScript中检查对象是否存在后如何跳过循环 - How to skip a loop after checking existence in an object in JavaScript 根据特定值检查 Javascript 中的数组中是否存在 object - Checking existence of object in Array in Javascript based on a particular value 在 javascript 中,是否存在嵌入式 object 每一层的语法快捷方式检查? - in javascript, is there syntatic shortcut checking existence of each layer of embedded object? 检查物业是否存在的最佳做法 - Best practice on checking for property existence 如何在JavaScript的嵌套对象中检查是否存在空对象? - How to check for the existence of a null object in a nested object in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM