如何将二维数组组合成多级联动的格式

萌新i
  • 7

要将[

['广东省','广州市','番禺区','市桥街道'],
['广东省','广州市','番禺区','大石街道'],
['广东省','广州市','番禺区','桥南街道'],
['广东省','广州市','番禺区','洛浦街道'],
['广东省','广州市','番禺区','沙头街道']

]组合成[{

    text: "广东省",
    value: "广东省",
    children: [
      {
        text: "广州市",
        value: "广州市",
        children: [
          {
            text: "番禺区",
            value: "番禺区",
            children: [
              {
                text: "市桥街道",
                value: "市桥街道"
              },
              {
                text: "大石街道",
                value: "大石街道"
              },
              {
                text: "桥南街道",
                value: "桥南街道"
              },
              {
                text: "洛浦街道",
                value: "洛浦街道"
              },
              {
                text: "石壁街道",
                value: "石壁街道"
              },
              {
                text: "钟村街道",
                value: "钟村街道"
              },
              {
                text: "大龙街道",
                value: "大龙街道"
              },
              {
                text: "沙头街道",
                value: "沙头街道"
              }
            ]
          }
        ]
      }
    ]
  }]

这种格式,一到四级不一定

回复
阅读 372
2 个回答
✓ 已被采纳
function map(list) {
    function obj2arr(obj) {
        return Object.entries(obj).map(([key, value]) => ({
            text: key,
            value: key,
            children: value ? obj2arr(value) : null // 不想要children的key可以稍微修改下
        }))
    }
    
    return obj2arr(list.reduce((res, arr) => {
        arr.reduce((cur,v,i) => cur[v] ||= i == arr.length-1 ? null : {}, res);
        return res;
    }, {}))
}
function listToTree(list) {
    const result = [];
    list.forEach(textList => {
        let siblings = result;
        for(const text of textList) {
            let data = siblings.find(data => data.text === text);
            if (!data) {
                data = { text, value: text, children: [] };
                siblings.push(data);
            }
            siblings = data.children;
        }
    });
    return result;
}

const list = [
    [1, 2, 3],
    [1, 2, 4],
    [11, 22, 33],
];

console.log(listToTree(list));
宣传栏