4

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.

4
  • Can the same Id appear in your structure more than once? Commented Sep 11, 2011 at 21:24
  • Use recursion to walk down the tree and build the parent list each iteration. Commented Sep 11, 2011 at 21:25
  • What's your goal with this type of data-structure? It feels like you're going to have to loop through everything to get what you want. Commented Sep 11, 2011 at 21:25
  • @rwilliams nested categories. Commented Sep 11, 2011 at 21:29

2 Answers 2

9

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/

Sign up to request clarification or add additional context in comments.

Comments

1

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!

2 Comments

Thanks, I really don't think this is the way to go, it's a rather large library for something simple
Yes I understand and I agree! I just thought I'd edit my answer with the reasons why I didn't think it was appropriate in case folk wanted to see my reasoning :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.