我有两个数组
["a", "b", "c"]
["a", "b", "d"]
我想将它转换为
{
a :
{
b :
{
c : null,
d : null
}
}
}
我该怎么做?
我有两个数组
["a", "b", "c"]
["a", "b", "d"]
{
a :
{
b :
{
c : null,
d : null
}
}
}
var tree = {}
function addToTree(tree, array) {
for (var i = 0, length = array.length; i < length; i++) {
tree = tree[array[i]] = tree[array[i]] || {}
}
}
addToTree(tree, ["a", "b", "c"])
addToTree(tree, ["a", "b", "d"])
/*{
"a": {
"b": {
"c": {},
"d": {}
}
}
}*/
唯一它不做的就是将树的叶子节点设置为 null,而是将它们设置为空对象。这样可以吗?
如果您想要叶子节点是 null,则可以使用以下代码:
function addToTree(tree, array) {
for (var i = 0, length = array.length; i < length; i++) {
tree = tree[array[i]] = ((i == length - 1) ? null : tree[array[i]] || {})
}
}
// or, without the i == length - 1 check in each iteration:
function addToTree(tree, array) {
for (var i = 0, length = array.length; i < length -1; i++) {
tree = tree[array[i]] = tree[array[i]] || {};
}
tree[array[i]] = null;
}
/*{
"a": {
"b": {
"c": null,
"d": null
}
}
}*/
var
:var i = 0, length = array.length
- Marcel Korpel