省市区树结构扁平化转换结构,省市区回显?

结构:
只有当前节点层级有选中标识位,其他都是null
一级选中只有当前一级得check = 1,其他都是null
二级选中只有当前二级的check=1,其他都是null
三级选中只有当前三级的check=1,其他都是null

数据:

 [
    {
      "code": "110000",
      "value": "北京市",
      "check":1,
      "children": [
        {
          "code": "110100",
          "value": "北京市",
          "check":null,
          "children": [{
            "code": "110101",
            "value": "东城区",
            "check":null
          }, {
            "code": "110102",
            "value": "西城区",
            "checked":null
          }]
        }
      ]
    },
    {
      "code": "130000",
      "value": "河北省",
      "check":null,
      "children":[
        {
          "code": "130100",
          "value": "石家庄市",
          "check":"1",
          "children": [{
            "code": "130102",
            "value": "长安区",
            "check":null
          }, {
            "code": "130104",
            "value": "桥西区",
            "check":null
          }]
        },
        {
          "code": "130200",
          "value": "唐山市",
          "check": null,
          "children": [{
            "code": "130202",
            "value": "路南区",
            "check": null,
          }, {
            "code": "130203",
            "value": "路北区",
            "check": null,
          }]
        }
      ]
    },
    {
      "code": "150000",
      "value": "内蒙古自治区",
      "check":null,
      "children":[
        {
          "code": "150100",
          "value": "呼和浩特市",
          "check":null,
          "children": [{
            "code": "150102",
            "check":null,
            "value": "新城区"
          }, {
            "code": "150103",
            "check":1,
            "value": "回民区"
          }]
        }
      ]
    }
  ]

结果:
选中的1,2,3级code
如:
[

[110000,110100,110101],
[110000,110100,110102],
[130000,130100,130102],
[130000,130100,130104],
[150000,150100,150103]

]

请问怎么解,求搭救

阅读 2k
2 个回答

主要是进行递归,将选中态传递下去。

/**
 * 获取所有被选中的code
 * @param {any[]} list 树形结构
 * @param {string[]} parentList 到父级所有的code的数组
 * @param {boolean} parentChecked 上级是否被选中,若上级被选中,则下面所有的子选项均是被选中的数据
 */
const getCheckedList = (list, parentList = [], parentChecked = false) => {
  let result = [];

  if (!Array.isArray(list)) {
    return result;
  }

  list.forEach((item) => {
    const checked = parentChecked || item.check; // 父级被选中或当前被选中,均认为是被选中
    const codeList = parentList.concat(item.code);

    if (item.children) {
      // 当前不是最内层
      result = result.concat(getCheckedList(item.children, codeList, checked));
    } else {
      // 已到最内层
      if (checked) {
        result.push(codeList);
      }
    }
  });

  return result;
};

使用:

console.log(getCheckedList(tree));

image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题