1. 树状结构数据搜索
树状结构数据中搜索并返回匹配特定 branchName 的对象,我们可以编写一个递归函数。下面是一个用 JavaScript 编写的示例函数,它接受树状数据和目标 branchName 作为参数,并返回找到的对象(如果有多个匹配,可以返回一个数组)。
代码语言:javascript复制function searchTreeForBranchName(treeData, targetBranchName) {
let results = [];
function search(node) {
// 如果当前节点的 branchName 匹配目标,将其添加到结果数组中
if (node.branchName === targetBranchName) {
results.push(node);
}
// 如果当前节点有 children 属性且是一个数组,遍历子节点
if (Array.isArray(node.children)) {
node.children.forEach(child => {
search(child); // 递归搜索子节点
});
}
}
// 从根节点开始搜索
treeData.forEach(rootNode => {
search(rootNode);
});
return results;
}
// 示例使用
const treeData = [
{
"craftId": "1737034670929321985",
"craftName": "厌氧单元",
"saveDigit": 2,
"delFlag": 0,
"deviceId": "1742786513379852289",
"deviceName": "厌氧罐-01",
"valleyElecPrice": 0,
"orgId": "4",
"updateBy": null,
"children": [
{
"craftId": "1737673712465338369",
"craftName": "预处理单元",
"saveDigit": 0,
"delFlag": 0,
"deviceId": "",
"deviceName": "",
"valleyElecPrice": 0,
"orgId": "4",
"updateBy": null,
"children": null,
"sortBy": 1,
"id": "1800770518751703041",
"meterAutomatic": "2",
"variableName": "",
"flatElecPrice": 0,
"elecPrice": 1.5,
"factoryId": "1740175059734216705",
"branchName": "支路1-1",
"updateTime": null,
"spikeElecPrice": 0,
"variableId": "",
"parentId": "1742837293533167618",
"electricType": "1",
"peakElecPrice": 0,
"createBy": "4-admin",
"createTime": "2024-06-12 14:02:03",
"doubleRate": "2"
}
],
"sortBy": 1,
"id": "1742837293533167618",
"meterAutomatic": "2",
"variableName": "",
"flatElecPrice": 0,
"elecPrice": 1.5,
"factoryId": "1740175059734216705",
"branchName": "支路1",
"updateTime": null,
"spikeElecPrice": 0,
"variableId": null,
"parentId": "0",
"electricType": "1",
"peakElecPrice": 0,
"createBy": "4-admin",
"createTime": "2024-01-04 17:16:06",
"doubleRate": "2",
"electricType_dictText": "均值电价"
}
];
const targetBranchName = "支路1";
const foundNodes = searchTreeForBranchName(treeData, targetBranchName);
console.log(foundNodes);
2. 两组数组去重合并
代码语言:javascript复制addMissingElements(optionArr, resultArr) {
// 创建一个 Set 以存储 optionArr 中的元素,便于快速查找
const setOptionArr = new Set(optionArr.map(item => item.id)); // 假设 value 是用来唯一标识元素的属性
// 过滤 resultArr 中不在 setOptionArr 中的元素,并将其转换为与 arr1 相同格式的元素数组
const missingElements = resultArr.filter(item => !setOptionArr.has(item.id));
// 将缺失的元素添加到 optionArr 中
return [...optionArr, ...missingElements];
}