使用forEach动态创建嵌套对象

时间:2016-09-25 19:53:06

标签: javascript loops object

我有一个'路径'字符串:'profile.name.en';

我想用它来动态创建一个对象。我正在使用这个功能及其工作:

function set(obj, path, value) {
    var schema = obj;  // a moving reference to internal objects within obj
    var arr = path.split('.');
    var len = arr.length;

    for(var i = 0; i < len-1; i++) {
        var elem = arr[i];
        if( !schema[elem] ) schema[elem] = {};
        schema = schema[elem];
    }
    schema[arr[len-1]] = value;
    return schema;
}

像这样使用:

var a = {};
var path = 'profile.name.en';
var profileName = 'OleFrank';
var o = set(a, path, profileName);

// result
{
    profile: {
        name: {
            en: 'OleFrank'
        }
    }
}

我尝试重构使用forEach而不是for-loop,但之后它不再起作用了。这是为什么?

1 个答案:

答案 0 :(得分:0)

您可以使用Array#reduce,因为这会返回您需要的对象,而不会在外面保留引用。

function set(object, path, value) {
    var keys = path.split('.'),
        last = keys.pop();

    keys.reduce(function (o, k) {
        return o[k] = o[k] || {};
    }, object)[last] = value;
}

var a = {},
    path = 'profile.name.en',
    profileName = 'OleFrank';

set(a, path, profileName); // no need of an assignment, because of
                           // call by reference with an object

console.log(a);

版本为Array#forEach

function set(object, path, value) {
    var keys = path.split('.'),
        last = keys.pop();

    keys.forEach(function (k) {
        object[k] = object[k] || {};
        object = object[k];
    });
    object[last] = value;
}

var a = {},
    path = 'profile.name.en',
    profileName = 'OleFrank';

set(a, path, profileName);

console.log(a);