【发布时间】:2021-12-17 19:32:42
【问题描述】:
我想在递归数组中找到某项的父项
{
"uuid": "707a5ffd-68e2-4dbd-b539-128512ba3a0a",
"type": "page",
"items": [
{
"uuid": "9d823429-cc24-444d-a21c-a81357305851",
"title": "1",
"type": "question",
},
{
"type": "section",
"title": "2",
"uuid": "346dec94-124c-4932-bd40-af9dc68f1d27",
"items": [
{
"uuid": "bf0a9ab9-99cc-4833-b3d3-84a97072e85f",
"title": "2.1",
"type": "question",
}
],
},
{
"type": "section",
"title": "3",
"uuid": "4964096d-0de9-4ab1-ace5-e42516d6b866",
"items": [
{
"uuid": "b2170580-1e2e-4fb4-a7b9-a56b79db21b3",
"title": "3.1",
"type": "question",
}
],
}
],
"params": {
"collapsed": false
}
}
到目前为止我已经尝试过:
export const findItemParent = (items, id, parent = null) => {
if (parent && parent.id === id) {
return parent;
}
for (const item of items) {
if (Object.prototype.hasOwnProperty.call(item, 'items')) {
return findItemParent(item.items, id, item);
}
}
return parent;
};
那我打电话给findItemParent:
const data = [{...}]; // the data of the first snipet
// b2170580-1e2e-4fb4-a7b9-a56b79db21b3 -> item with title 3.1
const parent = findItemParent(data, "b2170580-1e2e-4fb4-a7b9-a56b79db21b3");
每当我运行此代码时,我都会得到父级 2。
在上面的例子中,我传递了标题为3.1 的项目的ID,所以逻辑上父级是3。如何获取给定 id 的任何项目的父项?
【问题讨论】:
-
当您尝试运行此代码时发生了什么?
-
@ScottHunter 我已经更新了添加沙箱的问题。谢谢你告诉我
标签: javascript arrays recursion