标签导航:

本文介绍如何将省市区三级嵌套数据扁平化,并根据选中状态调整层级信息。原始数据为树状结构,包含省、市、区三级信息(代码code、名称value和选中状态checked)。目标是根据选中状态,生成扁平化数据,并记录实际层级。

如何将省市区树状结构数据扁平化并根据选中状态调整层级信息?

原始数据结构示例:

[
  {
    "code": "110000",
    "value": "北京市",
    "checked": "1",
    "children": [
      {
        "code": "110100",
        "value": "北京市",
        "checked": "1",
        "children": [
          {
            "code": "110101",
            "value": "东城区",
            "checked": "1"
          },
          {
            "code": "110102",
            "value": "西城区",
            "checked": "1"
          }
        ]
      }
    ]
  },
  {
    "code": "120000",
    "value": "天津市",
    "checked": "1",
    "children": [
      {
        "code": "120100",
        "value": "天津市",
        "checked": "1",
        "children": [
          {
            "code": "120101",
            "value": "和平区",
            "checked": "0"
          },
          {
            "code": "120102",
            "value": "河东区",
            "checked": "1"
          }
        ]
      }
    ]
  }
]

目标数据结构: 根据选中状态,如果所有子级都选中,则只保留父级;如果部分子级选中,则保留所有选中级别的信息。

[
  {
    "provinceAreald": "110000",
    "cityAreald": null,
    "countryAreald": null,
    "actualAreaLevel": "1"
  },
  {
    "provinceAreald": "120000",
    "cityAreald": "120100",
    "countryAreald": "120102",
    "actualAreaLevel": "3"
  }
]

JavaScript实现: 以下代码通过递归函数实现数据转换:

function flattenData(data) {
  const result = [];
  function processNode(node, parent) {
    if (node.checked === "1") {
      const item = {
        provinceAreald: parent ? parent.code : node.code,
        cityAreald: null,
        countryAreald: null,
        actualAreaLevel: 1,
      };
      if (node.children) {
        const childrenChecked = node.children.filter(child => child.checked === "1");
        if (childrenChecked.length > 0) {
          item.actualAreaLevel = 1;
          childrenChecked.forEach(child => {
              item.cityAreald = child.code;
              item.actualAreaLevel = 2;
              if(child.children){
                  const grandChildrenChecked = child.children.filter(grandchild => grandchild.checked === "1");
                  if(grandChildrenChecked.length > 0){
                      grandChildrenChecked.forEach(grandchild => {
                          item.countryAreald = grandchild.code;
                          item.actualAreaLevel = 3;
                      })
                  }
              }
          })
        }
      }
      result.push(item);
    }
    if (node.children) {
      node.children.forEach(child => processNode(child, node));
    }
  }
  data.forEach(province => processNode(province));
  return result;
}

const newData = flattenData(data);
console.log(newData);

这段代码更简洁高效地实现了相同的功能,避免了原代码中不必要的函数嵌套和变量传递。 它直接在递归函数内部处理所有层级,并根据选中状态动态更新actualAreaLevel以及cityAreald和countryAreald的值。