maioyan icon indicating copy to clipboard operation
maioyan copied to clipboard

如何将城市的数据进行分类处理-

Open yaogengzhu opened this issue 5 years ago • 0 comments

现在有一个需求就是。

image

如何将数据处理成有格式的,并且进行排序,看代码

// 这里不写如何将数据通过api获取回来。直接开始处理数据 
 formatCityList(cities) {
// cities 就是获取回来的数据 
      console.log(cities)
// 存放处理好的数据
      var cityList = [];
      // 循环遍历传递过来的数据
      for (var i = 0; i < cities.length; i++) {
        // 取出数组中每个单词的字母
        var firstLetter = cities[i].py.substring(0, 1).toUpperCase();
        if (toCom()) { 
          cityList.push({
            index: firstLetter,
            list: [{ nm: cities[i].nm, id: cities[i].id }]
          });
        } else {
          // 累加到已有索引
          for (var j = 0; j < cityList.length; j++) {
            if (cityList[j].index === firstLetter) {
              cityList[j].list.push({ nm: cities[i].nm, id: cities[i].id });
            }
          }
        }
      }
      // 处理排序
      cityList.sort(function(a, b) {
        if (a.index > b.index) {
          return 1;
        } else if (a.index < b.index) {
          return -1;
        } else {
          return 0;
        }
      });

      //在写一个判断的函数
      function toCom() {
        for (var i = 0; i < cityList.length; i++) {
          if (cityList[i].index === firstLetter) {
            return false;
          }
        }
        return true;
      }
      // console.log(cityList)
      return cityList;
    }

以上方式可以将数据处理好,并且返回!

yaogengzhu avatar May 11 '19 10:05 yaogengzhu