前端大佬们,这段代码如何优化?
const getSelectedChildFacets = function (parent) { parent?.childrens?.forEach((child) => {
if (child.selected && !child.partiallySelected) {
// 如果是全选
if (parentValues.includes(child.value)) {
// 如果是父节点,非子节点则继续向下查找
getSelectedChildFacets(child);
} else {
// 如果是子节点,则存起来
arrSelectedFacets.push(child.value);
}
} else if (child.selected && child.partiallySelected) {
// 如果是半选,则继续向下查找
getSelectedChildFacets(child);
}
});
};
arrFacetValues.forEach((parent) => { if (parent.selected && !parent.partiallySelected) {
// 全选
if (parentValues.includes(parent.value)) {
// 全选且是父节点,向下查找
getSelectedChildFacets(parent);
} else {
// 子节点则存到树组中
arrSelectedFacets.push(parent.value);
}
}
if (parent.selected && parent.partiallySelected) {
// 如果是半选,继续向下查找
getSelectedChildFacets(parent);
}
});
如何将两个方法合并成一个方法
如图parentValues = ['BC', 'BC-SRV', 'BC-SRV-COM'],
想得到的是选中的树组arrSelectedFacets = ['BC-SRV-COM-FTP', 'BC-SRV-COM-TEL']
const arrFacetValues = [ {
value: "BC",
selected: true,
partiallySelected: true,
childrens: [
{
value: "BC-SRV",
selected: true,
partiallySelected: true,
childrens: [
{
value: "BC-SRV-COM",
selected: true,
partiallySelected: true,
childrens: [
{
value: "BC-SRV-COM-FTP",
selected: true,
partiallySelected: false,
childrens: [],
},
{
value: "BC-SRV-COM-TEL",
selected: true,
partiallySelected: false,
childrens: [],
},
],
}
],
}
],
}
]
如果 BC-SRV-COM 下的子节点都选中,则arrSelectedFacets=['BC-SRV-COM']
回答:
const getSelectedChildFacets = function (node, parentValues, arrSelectedFacets) { if (node.selected) {
if (!node.partiallySelected && !parentValues.includes(node.id)) {
arrSelectedFacets.push(node.id);
} else {
node.childrens.forEach((child) => {
getSelectedChildFacets(child, parentValues, arrSelectedFacets);
});
}
}
};
const parentValues = ['BC', 'BC-SRV', 'BC-SRV-COM'];
const arrSelectedFacets = [];
const arrFacetValues = [
{
id: "BC",
selected: true,
partiallySelected: true,
childrens: [
{
id: "BC-SRV",
selected: true,
partiallySelected: true,
childrens: [
{
id: "BC-SRV-COM",
selected: true,
partiallySelected: true,
childrens: [
{
id: "BC-SRV-COM-FTP",
selected: true,
partiallySelected: false,
childrens: [],
},
{
id: "BC-SRV-COM-TEL",
selected: true,
partiallySelected: false,
childrens: [],
},
],
}
],
}
],
}
];
arrFacetValues.forEach((parent) => {
getSelectedChildFacets(parent, parentValues, arrSelectedFacets);
});
console.log(arrSelectedFacets); // ['BC-SRV-COM-FTP', 'BC-SRV-COM-TEL']
以上是 前端大佬们,这段代码如何优化? 的全部内容, 来源链接: utcz.com/p/934811.html