Учитывая эти 4 переменные,
var el1 = {name:'ronaldo', team: 'europe/spain/realmadrid'}
var el2 = {name:'messi', team: 'europe/spain/barcelona'}
var el3 = {name:'gerald', team: 'europe/england/liverpool'}
var el4 = {name:'unknown english', team: 'europe/england'}
Я должен произвести эту древовидную иерархию JSON,
{
"text":"europe",
"leaf":false,
"children":[
{
"text":"spain",
"leaf":false,
"children":[
{
"text":"realmadrid",
"leaf":false,
"children":[
{
"text":"ronaldo",
"leaf":true
}
]
},
{
"text":"barcelona",
"leaf":false,
"children":[
{
"text":"messi",
"leaf":true
}
]
}
]
},
{
"text":"england",
"leaf":false,
"children":[
{
"text":"unknown english",
"leaf":true
},
{
"text":"liverpool",
"leaf":false,
"children":[
{
"text":"gerald",
"leaf":true
}
]
}
]
}
]
}
Было бы намного проще, если бы каким-то образом el1-el4 были объединены в один объект, например
var data = []
data[0] = {name:'ronaldo', team: 'europe/spain/realmadrid'}
data[1] = {name:'messi', team: 'europe/spain/barcelona'}
data[2] = {name:'gerald', team: 'europe/england/liverpool'}
data[3] = {name:'unknown english', team: 'europe/england'}
Так вы сможете хотя бы быстро просмотреть их при обработке.
Также было бы полезно узнать, почему вам нужно хранить это в виде JSON-дерева. Я имею в виду, что не все узлы являются одним и тем же видом, верно? Первый уровень - это континент, затем страна, затем название команды, а листья - это отдельные футболисты. Это довольно запутанная структура данных, и я не уверен, как она может быть полезна. В любом случае, возможно, будет полезнее сначала перевести ее в полевую структуру, а затем сгенерировать дерево.
Edit:. Хорошо, я подумал об этом немного больше и думаю, что что-то вроде этого может подойти.
var data = [];
data[0] = {name:'ronaldo', team: 'europe/spain/realmadrid'};
data[1] = {name:'messi', team: 'europe/spain/barcelona'};
data[2] = {name:'gerald', team: 'europe/england/liverpool'};
data[3] = {name:'unknown english', team: 'europe/england'};
var tree = {};
function fillTree(name,steps) {
current = null;
for (var y = 0; y < steps.length; y++) {
if (y==0) {
if (!tree.children||typeof tree.children == 'undefined'){
tree = { text: steps[y], leaf: false, children: [] };
}
current = tree.children;
} else {
current.push({ text: steps[y], leaf: false, children: [] })
current = current[current.length - 1].children;
}
}
current.push({ text: name, leaf: true })
}
for (x=0; x < data.length; x++) {
steps =data[x].team.split('/');
fillTree(data[x].name,steps)
}
Это создает объект JavaScript. Я оставляю на ваше усмотрение преобразовать его в JSON.
Обновление:
Да, я вижу, что старый скрипт всегда помещал запись на второй уровень, даже если она уже существовала. Это новая улучшенная функция FillTree:
var tree = {};
function fillTree(name,steps) {
var current = null,
existing = null,
i = 0;
for (var y = 0; y < steps.length; y++) {
if (y==0) {
if (!tree.children||typeof tree.children == 'undefined'){
tree = { text: steps[y], leaf: false, children: [] };
}
current = tree.children;
} else {
existing = null;
for (i=0; i < current.length; i++) {
if (current[i].text === steps[y]) {
existing = current[i];
break;
}
}
if (existing) {
current = existing.children;
} else {
current.push({ text: steps[y], leaf: false, children: [] });
current = current[current.length - 1].children;
}
}
}
current.push({ text: name, leaf: true })
}
Самый простой способ преобразовать этот объект в JSON, по-видимому, - использовать JSON.stringify(tree)
, хотя, по-видимому, это не поддерживается единообразно (см. JavaScript JSON Page).