javascript - 从父键获取值并将其传递给对象中的子键
问题描述
我的结构如下:
{
0: [{
"id": "1",
"parentId": "root",
"path": "root"
"children": [{
"id": "2",
"parentId": "1",
"path": "1/2",
"children": [
"id": "4",
"parentId": "2",
"path": "2/4"
]
}, {
"id": "3",
"parentId": "1",
"path": "1/3"
}]
}]
}
我有 key "path"
,现在是"parentId/id"
,但我想有从根到这个元素的路径,所以它应该看起来"root/parentId/id/parentId/it..."
等等。例如 path: "root/1/2/4"
。
如何动态地将值放入键"path"
中以获取根元素的完整路径?
解决方案
您将需要识别根节点并从其路径开始。
然后将每个连续的子 id 添加到路径末尾。
let obj = {
0: [{
"id": "1",
"parentId": "root",
"path": "root",
"children": [{
"id": "2",
"parentId": "1",
"path": "1/2",
"children": [{
"id": "4",
"parentId": "2",
"path": "2/4"
}]
}, {
"id": "3",
"parentId": "1",
"path": "1/3"
}]
}]
};
console.log(getRoute(obj[0][0], true)); // Identify root
function getRoute(node, isRoot) {
return node != null
? (isRoot
? (node.path + '/')
: ''
) + node.id + (node.children
? '/' + getRoute(node.children[0], false)
: '')
: '';
}
推荐阅读
- c - 在 Aerospike 中,使用 C 客户端在 ops 中指定 ttl 的触摸操作不会重置为指定值。它重置为默认配置值
- jenkins - 如何在 groovy Jenkins 管道中访问 stringParam
- reactjs - 在我的 React 项目中获取“无法将类作为函数调用”:throw new TypeError("Cannot call a class as a function");
- javascript - How to Import jQuery in page
- cupy - CuPy 错误:无法打开 nvrtc-builtins64_101.dll
- javascript - 无法读取 Angular 中未定义的属性“RecaptchaVerifier”
- reactjs - 如何删除与渲染数据无关的内容?
- android - 如何在 kotlin 中将 DocumentReference 类型转换为 Arraylist
- python - PySpark 模式匹配和分配关联值
- python - 如何在 Spyder 中打开笔记本?