Необходимо распарсить дерево (JSON) по шаблону
У меня есть построенное дерево, у дерева есть уровни вложенности (depth), стоит задача: взять 1 (depth : 1) уровени вложенности -> найти все его конечные дочерние элементы и положить в массив 1 уровня (пример то что на приходит и то что должно быть на выходе ниже)
На входе: пример дерева:
{
"id": "43",
"depth": 0,
"node": [
{
"id": "5106",
"depth": 1, // 1 УРОВЕНЬ
"node": [
{
"id": "5108",
"depth": 2, // КОНЕЧНЫЙ
"node": []
},
{
"id": "5110",
"depth": 2,
"node": [
{
"id": "5112",
"depth": 3, // КОНЕЧНЫЙ
"node": []
},
{
"id": "51993",
"depth": 3,
"node": [
{
"id": "51190",
"depth": 4, // КОНЕЧНЫЙ
"node": []
}
]
}
]
},
{
"id": "6758",
"depth": 2, // КОНЕЧНЫЙ
"node": []
},
{
"id": "6760",
"depth": 2, // КОНЕЧНЫЙ
"node": []
}
]
},
{
"id": "5107",
"depth": 1,
"node": [
{
"id": "5112",
"depth": 2, // КОНЕЧНЫЙ
"node": []
},
{
"id": "5113",
"depth": 2, // КОНЕЧНЫЙ
"node": []
},
]
},
{
"id": "26517",
"depth": 1,
"node": []
},
]
}
На выходе (то что нужно получить):
{
"id": "43",
"depth": 0,
"node": [
{
"id": "5106",
"depth": 1,
"children": ["5108", "5112", "51190", "6758", "6760"]
},
{
"id": "5107",
"depth": 1,
"children": ["5112", "5113"]
},
{
"id": "26517",
"depth": 1,
"children": []
},
]
}
const input = {
"id": "43",
"depth": 0,
"node": [
{
"id": "5106",
"depth": 1, // 1 УРОВЕНЬ
"node": [
{
"id": "5108",
"depth": 2, // КОНЕЧНЫЙ
"node": []
},
{
"id": "5110",
"depth": 2,
"node": [
{
"id": "5112",
"depth": 3, // КОНЕЧНЫЙ
"node": []
},
{
"id": "51993",
"depth": 3,
"node": [
{
"id": "51190",
"depth": 4, // КОНЕЧНЫЙ
"node": []
}
]
}
]
},
{
"id": "6758",
"depth": 2, // КОНЕЧНЫЙ
"node": []
},
{
"id": "6760",
"depth": 2, // КОНЕЧНЫЙ
"node": []
}
]
},
{
"id": "5107",
"depth": 1,
"node": [
{
"id": "5112",
"depth": 2, // КОНЕЧНЫЙ
"node": []
},
{
"id": "5113",
"depth": 2, // КОНЕЧНЫЙ
"node": []
},
]
},
{
"id": "26517",
"depth": 1,
"node": []
},
]
}
function getOutput (input) {
let output = {
id: input.id,
depth: input.depth,
node: []
};
input.node.forEach(node => {
let children = getChildren(node);
output.node.push({
id: node.id,
depth: node.depth,
children: children
});
});
return output;
}
function getChildren (node) {
let children = [];
node.node.forEach(node => {
children.push(node.id);
children = children.concat(getChildren(node));
});
return children;
}
console.log(getOutput(input))
log ->
{
"id": "43",
"depth": 0,
"node": [
{
"id": "5106",
"depth": 1,
"children": [
"5108",
"5110",
"5112",
"51993",
"51190",
"6758",
"6760"
]
},
{
"id": "5107",
"depth": 1,
"children": [
"5112",
"5113"
]
},
{
"id": "26517",
"depth": 1,
"children": []
}
]
}
Источник: Stack Overflow на русском