使用命名空间/键搜索对象 [英] Search object with namespace / key

查看:56
本文介绍了使用命名空间/键搜索对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个可以在JavaScript对象中查找命名空间和值并返回密钥的函数。

I'm trying to write a function that can look up a namespace and value in a JavaScript object and return the key.

图像数据:

var o = {

    map: {
        lat : -33.86749,
        lng : 151.20699,
        zoom : 12
    },

    filters : {
        animals : {
            dogs: {
                myDog : 'fido'
            }
        }
    }
};

function get(namespace, key){
    //TODO
}

get('filters.animals.dogs', 'myDog')

如何动态构建一个函数 - 无论命名空间的深度如何?

How would you build a function that does this dynamically - no matter the depth of the namespace?

这个函数有点接近,只是它修改了我们不想要的原始对象:

This function is somewhat close, only it modifies the original object which we don't want ofcourse:

var get = function(obj, namespace, key, value) {

    var parts = namespace.split('.');

    for(var i = 0; i < parts.length; i++) {
        if(typeof obj[parts[i]] == 'undefined'){
            obj[parts[i]] = {};
        }

        obj = obj[parts[i]];
    }

    return obj[key] = value;
};

疯狂的原因是我不能暴露对象。它必须保持私有状态,公共方法必须吐出结果。

Reason for the madness is that I cannot expose the object. It must remain private and a public method must spit out a result.

推荐答案

试一试。

function get(namespace, key) {
    var parts = namespace.split('.'),
        i = 0,
        l = parts.length,
        obj = o;
    while ( i < l ) {
        obj = obj[parts[i]];
        if ( ! obj ) break;
        i++; 
    }
    return obj && obj[key] ? obj[key] : null;
}

这篇关于使用命名空间/键搜索对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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