JavaScript 求一地市条件过滤方法

cityList 地市全集
validSet 有效地市
将非有效地市删除,
如果validSet包含一个或多个,则其相对父级存在,其他子集删除
如果validSet不包含,则删除
最终返回有效地市结构,结构和原citylist结构一样。

/** 有效地市 */
  const validSet = ['000013', '000007'];
  const cityList = [
    {
    label: '全国',
    value: '000000',
    children: [
      {
        label: '陕西省',
        value: '000001',
        children: [
          {value: '000002', label: '西安市', isLeaf: true},
          {value: '000003', label: '渭南市', isLeaf: true},
        ],
      },
      {label: '上海', value: '000005', isLeaf: true},
      {label: '北京', value: '000006', isLeaf: true},
      {
        label: '河南省',
        value: '000007',
        children: [
          {value: '000008', label: '信阳', isLeaf: true},
          {value: '000009', label: '周口', isLeaf: true},
          {value: '000010', label: '其他', isLeaf: true},
        ],
      },
      {
        label: '山东省',
        value: '000011',
        children: [
          {value: '000012', label: '枣庄', isLeaf: true},
          {value: '000013', label: 'qit', isLeaf: true},
          {value: '000014', label: 'aa', isLeaf: true},
        ],
      },
    ]
  }];
阅读 1.9k
1 个回答
// 我理解的是保留 validSet存在的节点以及父级
function filterValidCity(cityList, validSet) {
 return    cityList.filter(item => {
        if (item.children) {
            item.children = filterValidCity(item.children, validSet)
        }
        return validSet.includes(item.value) || (item.children && item.children.length > 0)
    })
}

filterValidCity(cityList, validSet)

/* 结果
[{
  label: '全国',
  value: '000000',
  children: [
    {
      label: '河南省',
      value: '000007',
      children: []
    },
    {
        label: '山东省',
        value: '000011',
        children: [
            { value: '000013', label: 'qit', isLeaf: true }
        ]
    }
  ]
}]
*/

// 不改变数据源版
function filterValidCity(cityList, validSet) {
    return cityList.reduce((temp, item) => {
    let children = []
        if (item.children) {
            children = filterValidCity(item.children, validSet)
        }

        if (validSet.includes(item.value) || children.length > 0) {
            temp.push({ ...item , children})
        }
        return temp
    }, [])
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题