检查对象javascript中是否存在嵌套属性 [英] Checking existence of nested property in an object javascript

查看:197
本文介绍了检查对象javascript中是否存在嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经回顾了这个问题的一些答案,但是,我想以不同的方式提出我的问题。

I have already reviewed some of the answers to such question, however, I want to ask my question differently.

让我们说我们有一个字符串:level1.level2.level3。...表示名为 Obj 的对象中的嵌套属性。

Lets say we have a string like : "level1.level2.level3. ..." that indicates a nested property in an object called Obj.

关键是我们可能知道此字符串中存在多少嵌套属性。例如,它可能是level1.level2或level1.level2.level3.level4。

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".

现在,我想要一个给出 Obj的函数和作为输入的属性字符串,只需告诉我们,如果对象中存在这样的嵌套属性(假设输出为true或false)。

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).

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

Update: Thanks to @Silvinus, I found the solution with a minor modification:

        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;
    }


推荐答案

你可以探索你的Obj这个函数:

You can explore your Obj with this function :

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的嵌套属性,该属性取决于参数中传递的props

This function allow to explore nested property of Obj that depends of props passed in parameter

这篇关于检查对象javascript中是否存在嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆