javascript - 反向遍历层次结构
问题描述
我有一个包含父 ID 的对象层次结构。当我像这样解析 json 对象时,我将 parentId 添加到子对象中。
public static fromJson(json: any): Ancestry | Ancestry[] {
if (Array.isArray(json)) {
return json.map(Ancestry.fromJson) as Ancestry[];
}
const result = new Ancestry();
const { parents } = json;
parents.forEach(parent => {
parent.parentId = json.id;
});
json.parents = Parent.fromJson(parents);
Object.assign(result, json);
return result;
}
如果我有一个grandchild.id,关于如何拔出祖先的任何想法?
数据在 mockaroo curl ( Ancestry.json )
例如,使用以下 json 和 a grandchild.id = 5
,我将使用以下 ID 创建和排列
['5', '0723', '133', '1']
[{
"id": "1",
"name": "Deer, spotted",
"parents": [
{
"id": "133",
"name": "Jaime Coldrick",
"children": [
{
"id": "0723",
"name": "Ardys Kurten",
"grandchildren": [
{
"id": "384",
"name": "Madelle Bauman"
},
{
"id": "0576",
"name": "Pincas Maas"
},
{
"id": "5",
"name": "Corrie Beacock"
}
]
},
解决方案
可能有很多方法可以解决这个问题,但在我看来,最简单的方法是简单地在数据结构中进行搜索,并以与找到它们的时间相反的顺序存储 ID。这样输出就是你所追求的。
您也可以只是颠倒不同方法的顺序。
我想指出 json 结构有点奇怪。我原以为它只是有嵌套children
数组,而不是将它们重命名为parent
,children
和grandchildren
.
let data = [{
"id": "1",
"name": "Deer, spotted",
"parents": [
{
"id": "133",
"name": "Jaime Coldrick",
"children": [
{
"id": "0723",
"name": "Ardys Kurten",
"grandchildren": [
{
"id": "384",
"name": "Madelle Bauman"
},
{
"id": "0576",
"name": "Pincas Maas"
},
{
"id": "5",
"name": "Corrie Beacock"
}
]
}]
}]
}]
const expectedResults = ['5', '0723', '133', '1']
function traverseInverseResults(inputId, childArray) {
if(!childArray){ return }
for (const parent of childArray) {
if(parent.id === inputId){
return [parent.id]
} else {
let res = traverseInverseResults(inputId, parent.parents || parent.children || parent.grandchildren) // This part is a bit hacky, simply to accommodate the strange JSON structure.
if(res) {
res.push(parent.id)
return res
}
}
}
return
}
let result = traverseInverseResults('5', data)
console.log('results', result)
console.log('Got expected results?', expectedResults.length === result.length && expectedResults.every(function(value, index) { return value === result[index]}))
推荐阅读
- hdf5 - 是否可以复制整个 hdf5 文件并使用 h5copy 扩展外部链接?
- django - Django zip 使用 xhtml2pdf 生成的多个 PDF 文件
- vba - 用于在另一张表中查找单元格数据并更新它的 VBA 代码
- wordpress - docker-compose 在安装 wordpress 时锁定我的本地文件夹
- r - 当我在 R 中使用 Rcpp 时,包含 boost 的编译错误
- nginx - 用于 SEO 的 nginx 条件预渲染页面(if + try_files)
- android - Android 媒体播放器、数据源 api、三星 s8+
- android - Android 启动画面显示在系统栏后面
- glsl - GLSL 问题:坐标偏移和后退在不同的机器上产生不同的结果
- c++ - 中间部分不同的两个功能如何组织