searching a nested javascript object, getting an a

2019-03-31 09:22发布

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.

2条回答
【Aperson】
2楼-- · 2019-03-31 09:55

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!

查看更多
我想做一个坏孩纸
3楼-- · 2019-03-31 10:05

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/

查看更多
登录 后发表回答