将数组对象转化为类似于级联选择框要的输入

2021-09-11  本文已影响0人  Ag_fronted
const input = [
  { province: "广东", city: "深圳", area: "宝安" },
  { province: "广东", city: "深圳", area: "南山" },
  { province: "广东", city: "汕头", area: "潮阳" },
  { province: "广东", city: "广州", area: "天河" },
  { province: "浙江", city: "杭州", area: "西湖" },
];

function handleArea(arr) {
  const districtList = [];
  arr.forEach((v) => {
    let index = districtList.findIndex((item) => item.value === v.province);
    if (index === -1) {
      districtList.push({
        value: v.province,
        children: [
          {
            value: v.city,
            children: [
              {
                value: v.area,
              },
            ],
          },
        ],
      });
    } else {
      let cityIndex = districtList[index]["children"].findIndex(
        (item) => item.value === v.city
      );
      if (cityIndex === -1) {
        districtList[index]["children"].push({
          value: v.city,
          children: [{ value: v.area }],
        });
      } else {
        districtList[index]["children"][cityIndex]["children"].push({
          value: v.area,
        });
      }
    }
  });
  return districtList;
}

console.log(handleArea(input));

上一篇 下一篇

猜你喜欢

热点阅读