Javascript property inspector function (using closure)

吃可爱长大的小学妹 提交于 2019-12-11 08:55:44

问题


I am trying to write a function that can be used to inspect the properties of an object.

For example, for the given object:

var obj = {
    s : 'a',
    n : 1,
    d : new Date(),
    f : function(){},
    a : [],
    o : {
        a : {
            b: 'b'
        }
    }
};

I could use my inspector function to access to properties:

var ins = inspector(obj);
ins('s') // -> a
ins('n') // -> 1
ins('d') // -> 2018-12-06T11:51:26.244Z
ins('f') // -> [Function]
ins('a') // -> []
ins('o') // -> { a: { b: 'b' } }
ins('o.a') // -> { b: 'b' }
ins('o.a.b') // -> b
ins('o.p') // -> undefined
ins('o.p.p') // -> undefined
ins('p') // -> undefined
ins('') // -> undefined

My first approach:

function inspector(obj){
    return function fun (prop){
        console.log(obj[prop])
    }
}

However, it does not works properly for some situations:

ins('o.a') // -> { b: 'b' }
ins('o.a.b') // -> b
ins('o.p') // -> undefined
ins('o.p.p') // -> undefined

How could I rewrite my function to adapt to these cases?


回答1:


You can use reduce to get the value. First, you need to split the path by .:

function inspector(obj){
    return function fun (prop){
        return prop.split(".").reduce(function(o, p) {  // for each part p in prop.split(".")
            return o && o[p];                           // if o is an object truthy return o[p]
        }, obj);                                        // pass obj as the initial o
    }
}

The test o && is very basic. If you want to subscript o if and only if o is an object then replace that line with:

return (o && typeof o === "object")? o[p]: undefined;

Which returns o[p] if o is an object, otherwise undefined.

Example:

function inspector(obj){
    return function fun (prop){
        return prop.split(".").reduce(function(o, p) {
            return (o && typeof o === "object")? o[p]: undefined;
        }, obj);
    }
}

var obj = {
    s : 'a',
    n : 1,
    d : new Date(),
    f : function(){},
    a : [],
    o : {
        a : {
            b: 'b'
        }
    }
};

var ins = inspector(obj);

console.log('s:', ins('s'));          // -> a
console.log('n:', ins('n'));          // -> 1
console.log('d:', ins('d'));          // -> 2018-12-06T11:51:26.244Z
console.log('f:', ins('f'));          // -> [Function]
console.log('a:', ins('a'));          // -> []
console.log('o:', ins('o'));          // -> { a: { b: 'b' } }
console.log('o.a:', ins('o.a'));      // -> { b: 'b' }
console.log('o.a.b:', ins('o.a.b'));  // -> b
console.log('o.p:', ins('o.p'));      // -> undefined
console.log('o.p.p:', ins('o.p.p'));  // -> undefined
console.log('p:', ins('p'));          // -> undefined
console.log(':', ins(''));            // -> undefined


来源:https://stackoverflow.com/questions/53660608/javascript-property-inspector-function-using-closure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!