循环json数组以查找父对象,然后查找父对象的父对象

时间:2011-07-27 16:25:18

标签: javascript

我在数组中有许多对象,它们都有一个parentID(0表示没有父级 - 顶级)。 给定一个项目,我需要循环遍历数组并构建一个对象的谱系。 有谁知道这样做的功能?我试图不重新发明轮子而不确定要搜索什么。

感谢

2 个答案:

答案 0 :(得分:1)

是的,请使用此代码:(我已经为您复制并粘贴了我的笔记)

    success: function(msg){   //success response from an AJAX request
        var obj=JSON.parse(msg);
        for(var i=0;i<Object.size(obj);i++){
        var job=obj[i];
        var startDate=job['startDate'];
        var id=job['id'];
        var area=job['area'];
        var nDays=job['nDays'];
        //etc.
        }

其中Object.size定义为:

Object.size=function(obj){
    var size=0,key;
    for (key in obj){
        if(obj.hasOwnProperty(key)) size++;
    }
    return size;
};

答案 1 :(得分:0)

这实现了一个基于id和parentId的简单通用树:

function Node(obj) {
  this.data     = obj;
  this.parent   = null;
  this.children = [];
}
function Tree(objArray, idField, parentIdField) {
  this.index = {0: new Node()};

  // build an index by the value of idField
  for (var i=0, j=objArray.length; i<j; i++) {
    var currObj    = objArray[i];  

    this.index[ currObj[idField] ] = new Node(currObj);
  }
  // link the individual objects to a tree
  for (var i=0, j=objArray.length; i<j; i++) {
    var currObj    = objArray[i],
        currNode   = this.index[ currObj[idField] ],
        parentNode = this.index[ currObj[parentIdField] ];

    if (parentNode) {
      currNode.parent = parentNode;
      parentNode.children.push(currNode);
    }
  }
}

现在我们可以测试一下:

var testArray = [
  {id: 1, parent: 0, name: "Test 1"},
  {id: 2, parent: 0, name: "Test 2"},
  {id: 3, parent: 1, name: "Test 1.1"},
  {id: 4, parent: 1, name: "Test 1.2"},
  {id: 5, parent: 3, name: "Test 1.1.1"},
  {id: 6, parent: 2, name: "Test 2.1"}
];

var tree = new Tree(testArray, "id", "parent");

var root = tree.index[0];

for (var i=0; i<root.children.length; i++) {
  console.log(root.children[i].data.name);
}
// "Test 1"
// "Test 2"

console.log(tree.index[5].parent.data.name);
// "Test 1.1"