gpt4 book ai didi

javascript - 在数组中查找元素并返回父元素

转载 作者:行者123 更新时间:2023-12-03 16:48:30 28 4
gpt4 key购买 nike

我在尝试获取数组中找到的元素的父元素时遇到问题。

例如这是我的数组:

const arr = [
{
name: 'first level',
selected: true,
subItems: [
{
name: 'second level 1',
selected: false,
subItems: [],
},
{
name: 'second level 2',
selected: true,
subItems: [
{
name: 'third level 1',
selected: false,
subItems: [],
},
{
name: 'third level 2',
selected: false,
subItems: [],
},
{
name: 'third level 3',
selected: false,
subItems: [],
}
]
},
{
name: 'second level 3',
selected: false,
subItems: [
{
name: 'third level 4',
selected: false,
subItems: []
}
]
}
]
}
];

所以基本上,如果键 selected 为真,我想返回它的父元素。现在我不知道这个数组能有多深,所以我对这个问题采用了递归方法。

const getParent = (items, parentCat = null) => {
if (items && items.length > 0) {
const selectedCat = items.find(item => item.selected === true);
if (selectedCat && selectedCat.subItems.length > 0) {
return getParent(selectedCat.subItems, selectedCat);
}
return parentCat;
}
};

const parent = getParent(arr);

但是该代码仅在某些情况下适用于所选项目没有子项目的情况。我想获得最深的选定元素的父项。

编辑:如果任何元素选择了 true,那么它的父元素也将是 true,而且每个级别总是只有一个被选中的元素。

最佳答案

问题是在递归中,如果没有选择任何项目,则必须返回父项的父项。您可以通过在最深的递归中返回 null 来实现这一点,并让调用者在堆栈展开时处理它。

const getParent = (items, parent = null) => {
const selectedItem = items.find(item => item.selected === true);
if (selectedItem) {
// if there was a deeper parent, return that
// otherwise return my own parent
return getParent(selectedItem.subItems, selectedItem) || parent;
} else {
return null;
}
};

const arr = [
{
name: 'first level',
selected: true,
subItems: [
{
name: 'second level 1',
selected: false,
subItems: [],
},
{
name: 'second level 2',
selected: true,
subItems: [
{
name: 'third level 1',
selected: false,
subItems: [],
},
{
name: 'third level 2',
selected: false,
subItems: [],
},
{
name: 'third level 3',
selected: false,
subItems: [],
}
]
},
{
name: 'second level 3',
selected: false,
subItems: [
{
name: 'third level 4',
selected: false,
subItems: []
}
]
}
]
}
];

const getParent = (items, parent = null) => {
const selectedItem = items.find(item => item.selected === true);
if (selectedItem) {
return getParent(selectedItem.subItems, selectedItem) || parent;
} else {
return null;
}
};

console.log(getParent(arr));

关于javascript - 在数组中查找元素并返回父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60385490/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com