开发者

Create nested object with array values

I have array of keys:

var keys = ['key1', 'key2', 'key3'];

How can I create such object in a simplest way?

var object = { 'key1' : { 'key2' : {'key3' : 开发者_开发问答'value' }}}


You could make use of the fact that JavaScript stores references for Objects:

var keys = ['key1', 'key2', 'key3']; // input data
var object = {};                     // output data
var current = object;                // we will use this to recursively insert
                                     // a new object

for(var i = 0; i < keys.length; i++) { // iterate through input data

    if(i === keys.length - 1) {    

        current[keys[i]] = 'value'; // if it's the last element, insert 'value'
                                    // instead of a new object

    } else {

        current[keys[i]] = {};      // otherwise insert a new element in the
                                    // current object with key of 'key1' etc
                                    // (from input data)

        current = current[keys[i]]; // set current object to this one, so that
                                    // next time it will insert an object into
                                    // this newly created one

    }

}


How about this...

var keys = ['key1', 'key2', 'key3']; //initial array
var obj = stackArray(keys);          //obj will contain the nested object


function stackArray(arr){
    var obj = new Object;

    obj[arr.shift()] = (arr.length==0) ? 'value' : stackArray(arr)

    return obj
}

I don't particularly like using recursive functions but this seems to lend itself to your requirement.


In ES6, you can use .reduceRight() and computed property names:

let keys = ['key1', 'key2', 'key3'];

let obj = keys.reduceRight((a, c) => ({[c]: a}), 'value');

console.log(obj);

References:

  • Array.prototype.reduceRight()
  • Computed Property Names
  • Arrow Functions
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜