var array = [{"grandpa","father"}, {"father"}, {"grandpa","father","me"}];
鉴于上面的数组,我想生成一个类似下面的java脚本对象(JSON),它具有类似父子结构。
{"id":"grandpa",
"children":[
{"id":"father",
"children":[
{"id":"me",
"children":[]
}]
}]
}
答案 0 :(得分:7)
如果您正在询问如何获取层次结构路径列表并创建树结构,那么您可以在JavaScript中执行以下操作:
function convertToHierarchy(arry /* array of array of strings */)
{
var item, path;
// Discard duplicates and set up parent/child relationships
var children = {};
var hasParent = {};
for (var i = 0; i < arry.length; i++)
{
var path = arry[i];
var parent = null;
for (var j = 0; j < path.length; j++)
{
var item = path[j];
if (!children[item]) {
children[item] = {};
}
if (parent) {
children[parent][item] = true; /* dummy value */
hasParent[item] = true;
}
parent = item;
}
}
// Now build the hierarchy
var result = [];
for (item in children) {
if (!hasParent[item]) {
result.push(buildNodeRecursive(item, children));
}
}
return result;
}
function buildNodeRecursive(item, children)
{
var node = {id:item, children:[]};
for (var child in children[item]) {
node.children.push(buildNodeRecursive(child, children));
}
return node;
}
convertToHierarchy([["1","2"], ["1"], ["1","2","3"]]);
修改强>
你的问题仍然含糊不清。我之前的版本假设了这两件事:
在此示例中,我将假设以下内容:
以下是代码:
function convertToHierarchy(arry /* array of array of strings */)
{
// Build the node structure
var rootNode = {id:"root", children:{}}
for (var i = 0; i < arry.length; i++)
{
var path = arry[i];
buildNodeRecursive(rootNode, path, 0);
}
return rootNode;
}
function buildNodeRecursive(node, path, idx)
{
if (idx < path.length)
{
item = path[idx];
if (!node.children[item])
{
node.children[item] = {id:item, children:{}};
}
buildNodeRecursive(node.children[item], path, idx + 1);
}
}
返回层次结构,但格式有点不同。但是,你应该了解情况。
答案 1 :(得分:0)
我认为这应该有效。我正在使用firebug来跟踪输出的结构。
var el = {"name": "Level 1", "paths" : ["fruits"]};
var el2 = {"name": "Level 3", "paths" : ["fruits", "apples", "fuji"]};
var el3 = {"name": "Level 4", "paths" : ["fruits", "apples", "fuji", "red"]};
var el4 = {"name": "Level 2", "paths" : ["fruits", "apples"]};
var allEl = [el, el2, el3, el4];
/* Define recursive function for setting the child */
function setChild(parent, pos, arr, name)
{
if(pos < arr.length)
{
if(pos == arr.length-1) //last element of the paths
parent.name = name;
if(!parent.children){
parent.children = [];
parent.children[0] = new Object();
}
setChild(parent.children[0], pos + 1, arr, name);
}
}
/* Test starts here */
var root = new Object();
for(var i=0; i<allEl.length; i++)
{
var el = allEl[i];
setChild(root, 0, el.paths, el.name);
}
//Firefox debugging ...getfirebug.com
console.debug(root);
答案 2 :(得分:-3)
如果要编码JSON,只需使用JSON库。
不要尝试自己滚动。