const data = [
{
name:'北京',
shot:'bj'
},
{
name:'长沙',
shot:'ss'
},
{
name:'天津',
shot:'tj'
},
{
name:'沈阳',
shot:'sy'
},
{
name:'秦皇岛',
shot:'qhd'
},
{
name:'太原',
shot:'ty'
},
{
name:'宝鸡',
shot:'bj'
},
{
name:'上海',
shot:'sh'
},
]
// 处理数据的方法
const formatCityData = (list) => {
const cityList = {}
// 遍历数组
list.forEach((item) => {
// 获取每一个城市的首字母
const first = item.shot.substr(0,1)
console.log(first);
// 判断cityList中是否有改分类
if(cityList[first]) {
// 如果有,直接添加到数组
cityList[first].push(item)
}else{
// 如果没有,就新创建一个数组,然后把当前的信息添加到数组中
cityList[first] = [item]
}
})
// 用 Object.keys()方法获取索引数据并排序
const cityIndex = Object.keys(cityList).sort()
return {
cityList,
cityIndex
}
}
export default class Citylist extends React.Component {
componentDidMount() {
this.getCity()
}
getCity() {
const { cityList,cityIndex } = formatCityData(data)
console.log(cityList,cityIndex);
}
}
处理移动端长列表城市数据显示
最新推荐文章于 2024-06-10 21:57:03 发布