const data = [{
value: '110000',
label: "北京市",
children: [{
value: '110100',
label: "北京城区",
children: [
{
value: '110101',
label: "东城区",
children: [{
value: '111000',
label: '中心'
}]
},
{
value: '110102',
label: "西城区",
},
]
}]
}];
const ids = ['110000', '110100', '110101', '111000'];
function getLocationNames(ids, data) {
let names = [];
try {
if (Object.prototype.toString.call(data) == '[object Array]' && Object.prototype.toString.call(ids) == '[object Array]') {
let arr = [];
let children = [];
// 执行接下来的逻辑
for (let i = 0; i <= ids.length; i++) {
arr[i] = data.filter((child) => child.value == ids[i]);
names.push(...arr[i]);
if (ids.length == 1 || arr[i].length == 0) return names.map((name) => { return name.label }).join('/');
console.log(arr[i], 'i')
for (let j = 1; j <= ids.length - 1; j++) {
if (arr[i] && arr[i].length > 0 && arr[i][0] && arr[i][0].children) {
arr[j] = arr[j - 1][0].children.filter((child) => child.value == ids[j]);
names.push(...arr[j])
}
}
}
const labels = names.map((name) => { return name.label }).join('/')
return labels;
} else {
console.log('参数数据类型不正确!')
}
} catch{
console.log('异常操作')
}
}
function locationNames(ids, data) {
let names = [];
try {
if (Array.isArray(data) && Array.isArray(ids)) {
const getLabelByValue = (value, nodes) => {
const foundNode = nodes.find((node) => node.value === value);
if (!foundNode) {
throw new Error(`找不到与ID ${value} 对应的节点`);
}
names.push(foundNode.label);
if (foundNode.children && ids.includes(foundNode.children[0].value)) {
return getLabelByValue(ids.shift(), foundNode.children);
}
};
while (ids.length > 0) {
getLabelByValue(ids.shift(), data);
}
return names.join('/');
} else {
console.error('参数数据类型不正确!');
return null;
}
} catch (error) {
console.error('获取位置名称时发生错误:', error.message);
return null;
}
}
console.log(getLocationNames(ids, data), 'names')
console