汉字转拼音(分组,排序)"/>
js中文汉字转拼音(分组,排序)
碰到一个需求,需要把数组中每一项的name转成拼音,这里需要用到一个插件
js-pinyin 是一个js库,用来实现根据中文获取对应拼音
npm install js-pinyin --save
需要使用的页面中引入
import pinyin from 'js-pinyin'
他有个配置
setOptions中传入对象,对象可传两个参数
1.charCase参数: 输出拼音的大小写模式,0-首字母大写;1-全小写;2-全大写
2.checkPolyphone:是否检查多音字
pinyin.setOptions({checkPolyphone: false, charCase: 0});
//getFullChars: 获取拼音//getCamelChars: 获取拼音首字母console.log(pinyin.getFullChars('徐')); //Xuconsole.log(pinyin.getCamelChars('徐')); //X
目前有一个这样的需求,就是把每个城市按照a-z的顺序进行排序,做一个城市选择器的功能,但是我们对接高德的时候,返回的城市都不会进行分组排序,我们就要用到这个插件,首先提取每一个城市的首字母,然后按照a-z的顺序排序
对接高德高德web服务
这里在插件时长找了个别人封装好的插件(插件在这里),但是他的数据是有错误的,所以我们只能自己搞数据了
1.对接高德,获取城市数据
//获取高德城市数据
uni.request({url:'', // 搜索POI2.0data:{key:'5be8db92230ec3e651004b15aa19a577',subdistrict:2,},success: (res) => {// console.log('res',res.data.districts[0].districts);res.data.districts[0].districts.forEach(item=>{if(typeof item.citycode == 'object' ){getApp().globalData.city = getApp().globalData.city.concat(item.districts)}else{getApp().globalData.city = getApp().globalData.city.concat(item)}})console.log('1231231231232',getApp().globalData.city);console.log('最终结果',this.sortByFirstLetter(getApp().globalData.city));getApp().globalData.city = this.sortByFirstLetter(getApp().globalData.city)// getApp().globalData.city = getApp().globalData.city.sort((a,b)=>a.name.localeCompare(b.name,'zh'))}})
2.排序分组
这里用到了localeCompare()方法和sort()方法
localeCompare()方法返回一个数字来指示一个参考字符串是否在排序顺序前面或之后或与给定字符串相同
function sortByFirstLetter(origin) {// 将目标数据进行排序origin = origin.sort((pre, next) => pinyin.getFullChars(pre.name).localeCompare(pinyin.getFullChars(next.name)))const newArr = []origin.map(item => {// 取首字母const key = pinyin.getFullChars(item.name).charAt(0)const index = newArr.findIndex(subItem => subItem.key === key)if (index < 0) {newArr.push({key: key,list: [item]})} else {newArr[index].list.push(item)}})return newArr},
效果展示:
更多推荐
js中文汉字转拼音(分组,排序)
发布评论