【发布时间】:2015-12-14 21:35:37
【问题描述】:
有谁知道一种有效的方法来遍历复杂的 javascript 对象来定位父节点?我有一个对象被返回,我绑定到一个ivhTreeview。我可以让对象绑定,但是当我单击子项时,我需要派生父节点和祖父节点:
root Item/grandparent (Incident)
- parent (IncidentStartDate)
-child (2008)
-child (2009)
- and so on
我正在使用的对象示例如下所示
[
{
"label": "Document Type",
"value": "_oCommon.DocumentType",
"children": [
{
"label": "Incident(4891)",
"value": "Incident",
"$$hashKey": "object:84",
"__ivhTreeviewExpanded": true,
"selected": true,
"__ivhTreeviewIndeterminate": false,
"children": [
{
"label": "Incident Date",
"value": "DateIncidentStart",
"children": [
{
"$$hashKey": "object:364",
"label": "2008(810)",
"value": "01/01/2008"
},
{
"$$hashKey": "object:365",
"label": "2009(810)",
"value": "01/01/2009"
},
{
"$$hashKey": "object:366",
"label": "2010(864)",
"value": "01/01/2010"
},
{
"$$hashKey": "object:367",
"label": "2011(780)",
"value": "01/01/2011"
},
{
"$$hashKey": "object:368",
"label": "2012(826)",
"value": "01/01/2012"
},
{
"$$hashKey": "object:369",
"label": "2013(801)",
"value": "01/01/2013"
}
]
}
]
}
],
"$$hashKey": "object:70",
"__ivhTreeviewExpanded": true,
"selected": true,
"__ivhTreeviewIndeterminate": false
}
]
我在这里尝试完成的是递归地爬取树,这样如果我点击 2008,我可以看到父元素是 DateIncidentStart,它是 DocumentType: Incident 的子元素
我采用的方法是两个 for 循环,第一个循环在我的角度控制器中迭代最外面的集合(是的,这应该在服务中更远,但我现在只是想完成这项工作)
function getAggregateId(selectedNode, parentTree) {
vm.lastSelectedNode = selectedNode.value;
vm.lastSelectedNodeId = selectedNode.objectId;
vm.selectedNodeParent = parentTree;
//itterate the tree
for (var p = 0, tree = parentTree.length; p < tree; p++) {
//search each child object for the matching key
searchTheChildNode(p, parentTree, selectedNode);
}
}
对于参数,ivhTreeview 将返回所选节点和从中选择该节点的树,因此在下面的示例中,我有两个
节点:
{
"$$hashKey": "object:364",
"label": "2008(810)",
"value": "01/01/2008"
}
以及带有子对象的树:
[{
"label": "Incident Date",
"value": "DateIncidentStart",
[0] Object
[1] Object
[2] Object
[3] Object
[4] Object
[5] Object
[6] Object
...}]
函数 searchTheChildNode 执行嵌套循环
function searchTheChildNode(index, parent, node) {
for (var c = 0, child = parent[index].children.length; c < child; c++) {
for (var nc = 0, items = parent[index].children[c]; nc < items; nc++) {
if (parent[index].children[c].$$hashKey == node.$$hashKey) {
console.log('found the parent ' + parent[index].children[c].value);
}
}
}
};
我被卡住的地方是我可以看到循环正在运行,但是当 $$hasKey 的条件设置为 true 时,日志甚至永远不会发生,它只会继续滚动。我觉得语法上有问题,但我可以看到。
有没有人有任何建议或者在搜索这样的集合时是否有更好的方法来定位父项和祖父项?
感谢您的任何建议
【问题讨论】:
-
这或多或少是我在这种情况下采取的方法。据我所知,您不会使用 JSON 获得更有效的解决方案。我对这项技术知之甚少,所以我不能保证它,但我看到提到 LINQ for JavaScript。 linqjs.codeplex.com
-
我在网上找到的,如果你需要从嵌套对象中访问 js 对象的父对象,你可以在子对象中保存父对象的引用。
-
按照@Gonzalo 的建议,只需遍历对象一次并添加所有需要的对子节点的引用。
-
你有lodash或下划线吗?
-
如果您使用嵌套的 ng-repeat,那么您可以绑定一个在点击时获取父级的函数。分享你的 html,我会展示如何。
标签: javascript angularjs