2014-10-16 115 views
0

我有一個數組:使用Lodash將數組轉換爲嵌套對象,可以嗎?

["a", "b", "c", "d"] 

我需要將其轉換爲對象,但是在這種格式:

a: { 
    b: { 
    c: { 
     d: 'some value' 
    } 
    } 
} 

如果變種常見= [ 「一個」, 「B」,「C 」, 「d」],我想:

var objTest = _.indexBy(common, function(key) { 
    return key; 
} 
); 

但這只是導致:

[object Object] { 
    a: "a", 
    b: "b", 
    c: "c", 
    d: "d" 
} 

回答

4

由於您正在尋找陣列中的單個對象,因此使用_.reduce_.reduceRight是完成工作的理想選擇。我們來探討一下。

在這種情況下,從左到右工作會很困難,因爲它需要進行遞歸才能到達最內部的對象,然後再向外工作。所以讓我們嘗試_.reduceRight

var common = ["a", "b", "c", "d"]; 
var innerValue = "some value"; 

_.reduceRight(common, function (memo, arrayValue) { 
    // Construct the object to be returned. 
    var obj = {}; 

    // Set the new key (arrayValue being the key name) and value (the object so far, memo): 
    obj[arrayValue] = memo; 

    // Return the newly-built object. 
    return obj; 
}, innerValue); 

Here's a JSFiddle證明這個工程。

+0

儘管TO要求明確指出_lodash_,值得注意的是,JS可以做到這一點ootB:http://jsfiddle.net/7j6zrmqm/1/;)+1無論如何爲好的答案。 – 2014-10-16 21:41:12

+1

不幸的是,ES5並不總是一個可行的選擇。 – 2014-10-16 22:46:20

相關問題