1.工作中遇到查找树形结构中某一值的问题
已知树形结构数据如下
let data = [
{
"value": "NY",
"label": "农业",
"children": [
{
"value": "NY110",
"label": "种植小麦"
},
{
"value": "NY121",
"label": "种植玉米"
},
{
"value": "NY122",
"label": "种植大豆"
}
]
},
{
"value": "YZ",
"label": "养殖",
"children": [
{
"value": "YZ002",
"label": "养牛"
},
{
"value": "YZ003",
"label": "养鱼"
},
{
"value": "YZ004",
"label": "养羊"
}
]
}
];
要查找在其中 value = “NY110” 所对应的label值
// 假设要查找的 value
let targetValue = "NY110";
// 使用数组的 find 方法查找匹配的对象
let result = data.flatMap(item => item.children).find(item => item.value === targetValue);
// 如果找到匹配的对象,获取其 label 字段的值
if (result) {
let label = result.label;
console.log(label); // 输出:种植小麦
} else {
console.log("未找到匹配的数据");
}
2 对此方法执行逻辑的解析
使用flatMap()方法后children中的被取出并形成一个数组对象,
[
{ value: 'NY110', label: '种植小麦' },
{ value: 'NY121', label: '种植玉米' },
{ value: 'NY122', label: '种植大豆' },
{ value: 'YZ002', label: '养牛' },
{ value: 'YZ003', label: '养鱼' },
{ value: 'YZ004', label: '养羊' }
]
再从数组中采用find()方法查找对应的value,得到其对应的label值。