动态设置嵌套对象的属性 [英] Dynamically set property of nested object

查看:107
本文介绍了动态设置嵌套对象的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象可以是任意数量的级别,并且可以具有任何现有属性。
例如:

I have an object that could be any number of levels deep and could have any existing properties. For example:

var obj = {
    db: {
        mongodb: {
            host: 'localhost'
        }
    }
};

关于我想设置(或覆盖)属性如下:

On that I would like to set (or overwrite) properties like so:

set('db.mongodb.user', 'root');
// or:
set('foo.bar', 'baz');

属性字符串可以有任何深度,值可以是任何类型/东西。 >
如果属性键已经存在,则不需要合并作为值的对象和数组。

Where the property string can have any depth, and the value can be any type/thing.
Objects and arrays as values don't need to be merged, should the property key already exist.

上一个示例将生成以下对象:

Previous example would produce following object:

var obj = {
    db: {
        mongodb: {
            host: 'localhost',
            user: 'root'
        }
    },
    foo: {
        bar: baz
    }
};

我如何实现这样的功能?

How can I realize such a function?

推荐答案

此函数使用您指定的参数,应该在 obj 容器中添加/更新数据。请注意,您需要跟踪 obj 架构中的哪些元素是容器,哪些是值(字符串,整数等),否则您将开始抛出异常。

This function, using the arguments you specified, should add/update the data in the obj container. Note that you need to keep track of which elements in obj schema are containers and which are values (strings, ints, etc.) otherwise you will start throwing exceptions.

obj = {};  // global object

function set(path, value) {
    var schema = obj;  // a moving reference to internal objects within obj
    var pList = path.split('.');
    var len = pList.length;
    for(var i = 0; i < len-1; i++) {
        var elem = pList[i];
        if( !schema[elem] ) schema[elem] = {}
        schema = schema[elem];
    }

    schema[pList[len-1]] = value;
}

set('mongo.db.user', 'root');

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

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