【问题标题】:traverse from a specific point in json object and up to find all parents从 json 对象中的特定点遍历并向上查找所有父对象
【发布时间】:2018-03-15 02:02:55
【问题描述】:

我有一个这样的 json 对象

{
  "id": 1,
  "name": "A",
  "nodes": [
    {
      "id": 2,
      "name": "B",
      "nodes": [
        {
          "id": 3,
          "name": "C",
          "nodes": []
        }
      ]
    }
  ]
}

如果我输入对象的 id,让我们取 id: 3,我将如何扫描整个三个找到具有特定 id 的对象,然后向上扫描到最后一个父对象。

所以扫描完成后,我知道 C 有父 B,B 有父 A,所以我可以像 A-B-C 一样打印它

一切都基于我知道我想找到其父母的对象的 ID。

上述对象可以是任意长度,并且可以有许多节点和级别。因此,如果从特定级别开始,任何人都知道如何将级别遍历到顶级?

编辑:

当我尝试解析这个时

let data = [
  {
    "id": 1,
    "name": "name",
    "testing": "something",
    "nodes": [
      {
        "id": 11,
        "name": "name",
        "testing": "something",
        "nodes": []
      }
    ]
  },
  {
    "id": 2,
    "name": "name",
    "testing": "something",
    "nodes": []
  }
]

通过执行 JSON.parse(data) 到 json 对象我得到一个错误

SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)

也试过了

      let jsonObject = JSON.stringify($scope.data);
      jsonObject = JSON.parse(jsonObject);
      createTree(jsonObject, null, nodeData.id)

并得到不同的错误:

TypeError: obj.nodes is not iterable

【问题讨论】:

标签: javascript json


【解决方案1】:

做一个基本的DFS扫描,一路添加parent属性,找到节点就爬上去。

let jsonParsed = JSON.parse(`
{
	"id": 1,
	"name": "A",
	"nodes": [
		{
			"id": 2,
			"name": "B",
			"nodes": [
				{
					"id": 3,
					"name": "C",
					"nodes": []
				}
			]
		}
	]
}
`)

let arr = []

function climbTree(obj) {
	arr.unshift(obj.name)
	if (obj.parent) {
		climbTree(obj.parent)
	}
}

function createTree(obj, parent = null, targetId = null) {
	obj.parent = parent
	if (targetId === obj.id) {
		return climbTree(obj)
	}
	for (let node of obj.nodes) {
		createTree(node, obj, targetId)
	}
}

createTree(jsonParsed, null, 3)

console.log(arr.join('-'))

【讨论】:

  • 将 json 解析为 jsonParsed 对象时出错。查看我更新的问题,看看我卡在哪里
猜你喜欢
  • 2017-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-18
  • 2017-05-26
  • 2010-10-17
  • 2014-05-01
相关资源
最近更新 更多