首页 > 其他分享 >前端小技巧之 --- 【对象数组分类并排序】

前端小技巧之 --- 【对象数组分类并排序】

时间:2023-01-26 18:22:21浏览次数:44  
标签:key map name index --- let 数组 排序 id

当前需求是:把下面的数组,按照index值分类,再按照字母顺序排序

export const singerList=[{
    id:0,
    index:'Z',
    name:'周杰伦'
},{
    id:1,
    index:'X',
    name:'薛之谦'
},{
    id:2,
    index:'C',
    name:'蔡依林'
},{
    id:3,
    index:'D',
    name:'邓紫棋'
},{
    id:4,
    index:'J',
    name:'金志文'
},{
    id:5,
    index:'Z',
    name:'周深'
},{
    id:6,
    index:'C',
    name:'陈奕迅'
},{
    id:7,
    index:'Z',
    name:'张学友'
},{
    id:8,
    index:'L',
    name:'刘德华'
},{
    id:9,
    index:'M',
    name:'毛不易'
},{
    id:10,
    index:'W',
    name:'王菲'
},{
    id:11,
    index:'Z',
    name:'张韶涵'
},]

(1)先分类

normalList() {
      let list = singerList;
      let map = {};
      list.forEach((item, idx) => {
        let key = item.index;
        //如果map里不存在当前的index,则添加属性,并初始化
        if (!map[key]) {
          map[key] = {
            title: key,
            items: [],
          };
        }
        // 在当前属性的items里添加需要的项
        map[key].items.push({
          id: item.id,
          name: item.name
        });
      });
      return map
},

结果为:

(2)把map对象转成有序数组

let result=[]
//   把map对象转为数组
for(let key in map){
    result.push(map[key])
}

(3)依据字母排序:

//   排序
result.sort((a,b)=>{
    return a.title.charCodeAt(0)-b.title.charCodeAt(0)
})

(4)总的代码

<template>
  <div>
    <h1>歌手</h1>
  </div>
</template>
<script>
import { singerList } from "api/singer";
export default {
  data() {
    return {};
  },
  mounted() {
    console.log("歌手列表--分类后:--【数组--排序后】", this.normalList());
  },
  methods: {
    normalList() {
      let list = singerList;
      let map = {};
      list.forEach((item, idx) => {
        let key = item.index; //分类【A\B\C\D...】
        //如果map里不存在当前的index,则添加属性,并初始化
        if (!map[key]) {
          map[key] = {
            title: key, //标记每个分类【A\B\C\D...】
            items: [], //每个分类的数据项
          };
        }
        // 在当前属性的items里添加需要的项
        map[key].items.push({
          id: item.id,
          name: item.name,
        });
      });

      //   把map对象转为数组
      let result = [];
      for (let key in map) {
        result.push(map[key]);
      }

      //   排序
      result.sort((a, b) => {
        return a.title.charCodeAt(0) - b.title.charCodeAt(0);
      });
      return result;
    },
  },
};
</script>

 

标签:key,map,name,index,---,let,数组,排序,id
From: https://www.cnblogs.com/zhaoyingzhen/p/17068014.html

相关文章