使用JSON数据

时间:2017-06-29 10:13:16

标签: javascript performance recursion

我需要从JSON中表示的数据构造树结构作为对象和父关系。我已经实现了以下代码,它成功地完成了这项工作,但我不确定它是否能提供最佳性能(我的意思是尽可能少地进行迭代)。

请注意,树的根表示为parentobject相同。例如{"object":"A", "parent":"A"}

关于任何其他具有更好性能的实现的建议会有所帮助!!

var jsonInput =
[
{"object":"A", "parent":"A"},
{"object":"B", "parent":"A"},
{"object":"C", "parent":"A"},
{"object":"D", "parent":"B"},
{"object":"E", "parent":"B"},
{"object":"F", "parent":"D"},
{"object":"G", "parent":"D"},
{"object":"H", "parent":"E"},
{"object":"I", "parent":"E"},
{"object":"J", "parent":"C"},
{"object":"K", "parent":"C"},
{"object":"L", "parent":"J"},
{"object":"M", "parent":"J"},
{"object":"N", "parent":"K"},
{"object":"O", "parent":"K"},
{"object":"P", "parent":"N"},
{"object":"Q", "parent":"N"},
{"object":"R", "parent":"O"},
{"object":"S", "parent":"O"}
];

var root = getRoot();
root.childs = findChildrens(root);

console.log("The tree hierarchy is:")
console.log(root);

function getRoot() {
var root;
for (var counter = 0; counter < jsonInput.length; counter++){
	var item = jsonInput[counter];
	if(item.object === item.parent) {
		root = item;
		break;
	}
}

var returnValue = JSON.parse(JSON.stringify(root));
root.visited = true;
return returnValue;
}

function findChildrens(parentObject) {
var childs = [];
for (var counter = 0; counter < jsonInput.length; counter++){
	var item = jsonInput[counter];
	if(item.parent === parentObject.object && !item.visited) {
		var child = JSON.parse(JSON.stringify(item));
		item.visited = true;
		child.childs = findChildrens(child);
		childs.push(child);
	}
}
return childs;
}

1 个答案:

答案 0 :(得分:-1)

具有线性运行时的简单解决方案。

var data = [
  {"object":"A", "parent":"A"},
  {"object":"B", "parent":"A"},
  {"object":"C", "parent":"A"},
  {"object":"D", "parent":"B"},
  {"object":"E", "parent":"B"},
  {"object":"F", "parent":"D"},
  {"object":"G", "parent":"D"},
  {"object":"H", "parent":"E"},
  {"object":"I", "parent":"E"},
  {"object":"J", "parent":"C"},
  {"object":"K", "parent":"C"},
  {"object":"L", "parent":"J"},
  {"object":"M", "parent":"J"},
  {"object":"N", "parent":"K"},
  {"object":"O", "parent":"K"},
  {"object":"P", "parent":"N"},
  {"object":"Q", "parent":"N"},
  {"object":"R", "parent":"O"},
  {"object":"S", "parent":"O"}
];

var rootNodes = data.filter(function(node) {
  if (node.object in this)
    throw new Error("duplicate object " + node.object);

  this[node.object] = node;
  node.children = [];

  if (node.parent === node.object) return true;
  var parent = this[node.parent];

  if (!parent)
    throw new Error("invalid parent " + node.parent);

  parent.children.push(node);
}, Object.create(null));


console.log(rootNodes);
.as-console-wrapper {
  top: 0;
  max-height: 100%!important
}