我有兩個數組如何將數組轉換爲樹?
["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": {}
}
}
}*/
只有它不做的事情是將樹的葉子設置爲空 - 它將它們設置爲空對象。這可以嗎?
如果你想葉子爲空,然後用下面的代替:
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' – 2010-09-07 22:20:56
@Marcel Korpel:謝謝,修正。 – 2010-09-07 22:24:11
YUI的JSON實用程序可能會有所幫助,我還沒有把這個作爲一個答案,但因爲我不能告訴如果它能滿足你的需求,你可以直接擊球。或者,來想一想,檢查YUI的擴充實用程序,它會合並我相信的對象。 – danjah 2010-09-07 22:13:16
你在設計一個Trie嗎? – 2010-09-07 22:32:58