How to get the total depth of an unknown JSON hierarchy?
15019 просмотра
2 ответа
I've been struggling to find/build a recursive function to parse this JSON file and get the total depth of its children.
The file looks something like this:
var input = {
"name": "positive",
"children": [{
"name": "product service",
"children": [{
"name": "price",
"children": [{
"name": "cost",
"size": 8
}]
}, {
"name": "quality",
"children": [{
"name": "messaging",
"size": 4
}]
}]
}, {
"name": "customer service",
"children": [{
"name": "Personnel",
"children": [{
"name": "CEO",
"size": 7
}]
}]
}, {
"name": "product",
"children": [{
"name": "Apple",
"children": [{
"name": "iPhone 4",
"size": 10
}]
}]
}]
}
Автор: jfk83
Источник
Размещён: 13.11.2019 11:32
Ответы (2)
25 плюса
You can use a recursive function to go through the whole tree:
getDepth = function (obj) {
var depth = 0;
if (obj.children) {
obj.children.forEach(function (d) {
var tmpDepth = getDepth(d)
if (tmpDepth > depth) {
depth = tmpDepth
}
})
}
return 1 + depth
}
The function works as follow:
- If the object is not a leaf (i.e the object has the children attribute), then:
- Compute the depth of each child, save the maximal one
- return 1 + the depth of the deepest child
- Otherwise, return 1
jsFiddle: http://jsfiddle.net/chrisJamesC/hFTN8/
EDIT With modern JavaScript, the function could look like this:
const getDepth = ({ children }) => 1 +
(children ? Math.max(...children.map(getDepth)) : 0)
jsFiddle: http://jsfiddle.net/chrisJamesC/hFTN8/59/
Автор: Christopher Chiche Размещён: 18.04.2013 06:292 плюса
This will count the number of "leaves" in a tree:
var treeCount = function (branch) {
if (!branch.children) {
return 1;
}
return branch.children.reduce(function (c, b) {
return c + treeCount(b);
}, 0)
}
And an alternative way to get depth:
var depthCount = function (branch) {
if (!branch.children) {
return 1;
}
return 1 + d3.max(branch.children.map(depthCount));
}
Автор: minikomi
Размещён: 18.04.2013 06:33
Вопросы из категории :
- javascript Как определить, какой из указанных шрифтов был использован на веб-странице?
- javascript Валидация клиентской стороны ASP.Net
- javascript Длина объекта JavaScript
- javascript Получение текста из выпадающего списка
- javascript Скрипт входа со скрытыми кнопками
- json Безопасное превращение строки JSON в объект
- json Как я могу "красиво" отформатировать вывод JSON в Ruby on Rails?
- json Сериализация JSON в jQuery
- json Можете ли вы использовать запятую в JSON-объекте?
- json Можно ли использовать комментарии в формате JSON?
- d3.js D3 принудительно визуализирует макет очень медленно при использовании большого набора данных?
- d3.js Доступ к свойствам массива объектов
- d3.js Преобразование созданного JavaScript SVG в файл
- d3.js D3 Выбор элемента внутри SVG
- d3.js Каков наилучший способ сделать макет визуализации d3.js отзывчивым?
- nested Можно ли использовать регулярные выражения для сопоставления с вложенными шаблонами?
- nested Лучший способ сделать вложенную логику оператора в SQL Server
- nested Как сделать элемент дочерним по себе в XML-схеме?
- nested Вложенный класс в javascript, наследование приватных методов
- nested Несколько уровней «collection.defaultdict» в Python