Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

searching a nested javascript object, getting an array of ancestors

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.

like image 638
Harry Avatar asked Dec 27 '22 14:12

Harry


2 Answers

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/

like image 157
Guffa Avatar answered Jan 05 '23 19:01

Guffa


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!

like image 28
Paul Grime Avatar answered Jan 05 '23 19:01

Paul Grime