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

查看:28
本文介绍了检查对象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

这个函数允许探索依赖于传入参数的 props 的 Obj 嵌套属性

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

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

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