查找树形结构中某一数据value值的一种JS方法flatMap()

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值。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值