使用Lodash将数组转换为嵌套对象,是否可能?

时间:2014-10-16 21:26:15

标签: javascript lodash

我有一个数组:

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

我需要将其转换为对象,但采用以下格式:

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

如果var common = [" a"," b"," c"," d"],我试过:

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

但这只会导致:

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

1 个答案:

答案 0 :(得分: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证明这是有效的。