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('徐')); //Xu
 console.log(pinyin.getCamelChars('徐')); //X

目前有一个这样的需求,就是把每个城市按照a-z的顺序进行排序,做一个城市选择器的功能,但是我们对接高德的时候,返回的城市都不会进行分组排序,我们就要用到这个插件,首先提取每一个城市的首字母,然后按照a-z的顺序排序

对接高德高德web服务

这里在插件时长找了个别人封装好的插件(插件在这里),但是他的数据是有错误的,所以我们只能自己搞数据了

1.对接高德,获取城市数据

//获取高德城市数据
uni.request({
				url:'https://restapi.amap.com/v3/config/district', // 搜索POI2.0
				data:{
					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
			},

效果展示:

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值