searching a nested javascript object, getting an array of ancestors

坚强是说给别人听的谎言 提交于 2019-12-05 02:18:03

问题


I have a nested array like this:

array = [
    {
        "id": "67",
        "sub": [
            {
                "id": "663",
            },
            {
                "id": "435",
            }
        ]
    },
    {
        "id": "546",
        "sub": [
            {
                "id": "23",
                "sub": [
                 {
                     "id": "4",
                 }
             ]
            },
            {
                "id": "71"
            }
        ]
    }
]

I need to find 1 nested object by its id and get all its parents, producing an array of ids.

find.array("71")
=> ["546", "71"]

find.array("4")
=> ["546", "23", "4"]

What's the cleanest way to do this? Thanks.


回答1:


Recursively:

function find(array, id) {
  if (typeof array != 'undefined') {
    for (var i = 0; i < array.length; i++) {
      if (array[i].id == id) return [id];
      var a = find(array[i].sub, id);
      if (a != null) {
        a.unshift(array[i].id);
        return a;
      }
    }
  }
  return null;
}

Usage:

var result = find(array, 4);

Demo: http://jsfiddle.net/Guffa/VBJqf/




回答2:


Perhaps this - jsonselect.org.

EDIT: I've just had a play with JSONSelect and I don't think it's appropriate for your needs, as JSON does not have an intrinsic 'parent' property like xml.

It can find the object with the matching id, but you can't navigate upwards from that. E.g.

JSONSelect.match(':has(:root > .id:val("4"))', array)

returns me:

[Object { id="4"}]

which is good, it's just that I can't go anywhere from there!



来源:https://stackoverflow.com/questions/7381332/searching-a-nested-javascript-object-getting-an-array-of-ancestors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!