我有一个数组:
["a", "b", "c", "d"]
Run Code Online (Sandbox Code Playgroud)
我需要将其转换为对象,但格式如下:
a: {
b: {
c: {
d: 'some value'
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果 var common = ["a", "b", "c", "d"],我尝试过:
var objTest = _.indexBy(common, function(key) {
return key;
}
);
Run Code Online (Sandbox Code Playgroud)
但这只会导致:
[object Object] {
a: "a",
b: "b",
c: "c",
d: "d"
}
Run Code Online (Sandbox Code Playgroud)
由于您正在从数组中查找单个对象,因此使用_.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);
Run Code Online (Sandbox Code Playgroud)
这是一个 JSFiddle证明这是有效的。