gpt4 book ai didi

javascript - 如何根据叶子值显示 JSON 树的特定路径?

转载 作者:行者123 更新时间:2023-12-03 07:16:44 24 4
gpt4 key购买 nike

我有一个关于根据叶子的值显示树路径的问题,例如我有以下 JSON:

{
"children":
[
{
"children":
[
{
"name": "Predict Conversion"
}
],
"name": "Browser ID in {1}"
},
{
"children":
[
{
"name": "Predict Click"
}
],
"name": "Browser ID not in {1}"
}
],
"name": "Device Type ID in {1,3,4}"
}

我只想显示通向 value = "Predict Conversion"的叶子的完整路径

最佳答案

您可以使用递归来循环对象。使用 Array.isArray 测试 value 是否为 Array 类型,并且 typeof(obj)==="object" 为对象。

注意:typeof(obj) 将为 ArrayObject 返回 object

function searchInObj(obj, value, result) {

// check for array and call for every item
if (Array.isArray(obj)) {

// primary flag for array.
var r = false;
obj.forEach(function(item, index) {

// temporary flag for every iteration.
var _r = searchInObj(item, value, result);
if (_r) result.push(index)

// if one of element returned true, array should return true.
r = _r || r;
});
return r;
}

// If Object, loop over properties
else if (typeof(obj) === "object") {
for (var k in obj) {

// If object, check if property is Object/Array and call self.
if (typeof(obj[k]) === "object") {
var r = searchInObj(obj[k], value, result);
if (r) result.push(k);
return r;
}

// If property is not Array/Object, match value
else if (obj[k] === value) {
result.push(k);
return true;
}
// If no match, return false
else {
return false;
}
}
}
}

var data = {
"children": [{
"children": [{
"name": "Predict Conversion"
}],
"name": "Browser ID in {1}"
}, {
"children": [{
"name": "Predict Click"
}],
"name": "Browser ID not in {1}"
}],
"name": "Device Type ID in {1,3,4}"
}

var result = []
searchInObj(data, "Predict Conversion", result);
document.write("<pre>" + JSON.stringify(result.reverse(), 0, 4) + "</pre>");

注意:对于小型 JSON,这可行,但如果您的 JSON 很长,则这可能是非常昂贵的操作。

关于javascript - 如何根据叶子值显示 JSON 树的特定路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36397572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com