这个嵌套对象创建函数的lodash等价物是什么?

时间:2015-11-20 16:04:19

标签: javascript object lodash

所以,我有这个基于数组ok键创建嵌套对象的功能,我想知道如何使用lodash完成同样的事情?

// nest
var nest = function (obj, keys, v) {
    if (keys.length === 1) {
        obj[keys[0]] = v;
    } else {
        var key = keys.shift();
        obj[key] = nest(typeof obj[key] === 'undefined' ? {} : obj[key], keys, v);
    }
    return obj;
}


// sample data
var keys = ['user','name','fullName'];
var value = 'John Smith';

// create nested object
var obj = {};
obj = nest(obj, keys, value);

// log out new nested object
console.log(obj);

1 个答案:

答案 0 :(得分:1)

// include lodash somewhere...

// nest
var nest = function () {
    return _.set(obj, path, value);
}

// sample data
// var keys = ['user','name','fullName']; can use a path now!
var path = 'user.name.fullName';
var value = 'John Smith';

// create nested object
var obj = {};
obj = nest(obj, path, value);

// log out new nested object
console.log(obj);