searching a nested javascript object, getting an array of ancestors

北战南征 提交于 2019-12-03 21:29:09

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/

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!

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