Zve*_*989 2 javascript arrays sorting
我在尝试获取数组中找到的元素的父元素时遇到问题。
这是我的数组,例如:
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: []
}
]
}
]
}
];
Run Code Online (Sandbox Code Playgroud)
所以基本上如果选择的键为真,我想返回它的父元素。现在我不知道这个数组有多深,所以我对这个问题采取了递归的方法。
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);
Run Code Online (Sandbox Code Playgroud)
但是该代码仅在某些情况下适用于所选项目没有子项目的情况。我想获得最深选定元素的父项。
编辑:如果任何元素选择了 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;
}
};
Run Code Online (Sandbox Code Playgroud)
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;
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
130 次 |
| 最近记录: |