获取JSON对象内元素的路径

时间:2019-09-05 14:06:22

标签: javascript json search

我有一个如下对象:

[
  {
    "uid": "aaa-aaa",
    "name": "foo",
    "children": []
  },
  {
    "uid": "aaa-bbb",
    "name": "bar",
    "children": [
      {
        "uid": "aaa-bbc",
        "name": "baz",
        "children": []
      },
      {
        "uid": "aaa-ccc",
        "name": "fooz",
        "children": [
          {
            "uid": "aaa-bcb",
            "name": "Yeah !",
            "children": []
          }
        ]
      }
    ]
  }
]

我正在尝试编写一个函数,该函数将以该对象的uid作为参数,并返回该对象中具有uid的元素的路径(如果是null找不到)。

类似这样的东西:

> getElementPath(bigObject, 'aaa-bcb')
[1, "children", 1, "children", 0]
or
> getElementPath(bigObject, 'aaa-bcb')
[1, 1, 0]

我知道该函数必须是递归的,因为嵌套级别应该没有限制。我已经尝试过了,但是它总是返回null

function getElementPath (haystack, uid, currentPath = []) {
  if (haystack.uid === uid) {
    return currentPath
  }
  if (Array.isArray(haystack.children)) {
    for (let i = 0; i < haystack.children.length; i++) {
      let newPath = [...currentPath, i]
      let path = getElementPath(haystack.children[i], uid, newPath)
      if (path !== null) {
        return path
      }
    }
  }
  return null
}

2 个答案:

答案 0 :(得分:2)

我会使用flat

放平对象,然后在“对象”键上循环,直到找到具有适当值的键为止。找到它之后,关键就是路径。

https://www.npmjs.com/package/flat

我的(幼稚而又快速的)实现看起来像这样。但是我不喜欢它是因为它知道查看“ children”属性,如果数据结构定义良好且不经常更改,那很好,flat的想法会起作用无论您是否更改数据结构。

getPathForUid = (uid,obj,thisPath = []) => {

    if(Array.isArray(obj)) {
        return obj.reduce((acc,item,idx) => getPathForUid(uid,item,thisPath.concat(idx)),[]);
    }

    return obj.uid === uid ? thisPath : getPathForUid(uid,obj.children,thisPath.concat('children'));

}

答案 1 :(得分:0)

尝试一下:

    function getObject(listaJson, uid) {
    var object = null,
        param,
        type = null;

    if (listaJson.uid === uid) {
        return listaJson;
    }

    for (param in listaJson) {
        type = typeof(listaJson[param]);

        if (type.toString().toLowerCase() === 'object') {
            object = getObject(listaJson[param], uid);
        }

        if (object) {
            return object;
        }
    }

    return object;
}

console.log(getObject(json, 'aaa-aaa'));
console.log(getObject(json, 'aaa-bbb'));
console.log(getObject(json, 'aaa-bbc'));
console.log(getObject(json, 'aaa-ccc'));
console.log(getObject(json, 'aaa-bcb'));
console.log(getObject(json, 'aaa-xxx')); // null
console.log(getObject(json, 'yyy-jjj')); // null