简体   繁体   English

这个嵌套对象创建者函数的lodash等效项是什么?

[英]What’s the lodash equivalent of this nested object creator function?

So, I have this fuction that's creating nested objects based on an array ok keys and I'm wondering how I could accomplish the same thing using lodash? 因此,我有这种功能,可以根据数组的确定键创建嵌套对象,而我想知道如何使用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);
// 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM