两种形式:一种Json数据:{}, 一种Array数据:[]
1. 首先返回城市数据:
data: { list: [ { id: 1, firstletter: 'C', cityname: '长沙', pinyin: 'changsha', subjectCount: 5 }, { id: 2, firstletter: 'C', cityname: '常德', pinyin: 'changde', subjectCount: 0 }, { id: 3, firstletter: 'T', cityname: '天津', pinyin: 'tianjin', subjectCount: 0 }, { id: 4, firstletter: 'X', cityname: '西安', pinyin: 'xian', subjectCount: 0 }, ...... ], total: 10 },
2. 运用js 处理数据
1) Array篇
export function citysfil (citys) { const FristPin = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] const cityArray = [] const cityJson = {} for (let i = 0; i < FristPin.length; i++) { cityJson[FristPin[i]] = citys.filter(function (value) { return value.firstletter === FristPin[i] }) cityArray[i] = { pinyin: FristPin[i], item: cityJson[FristPin[i]] } } return cityArray }
得出的结果是:
[ { item: [], pinyin: 'A' }, { item: [], pinyin: 'B' }, { item: [ { cityname: '长沙', firstletter: 'C', id: 1, pinyin: 'changsha' }, { cityname: '常德', firstletter: 'C', id: 2, pinyin: 'changde' }, ...... ], pinyin: 'C' }, { item: [], pinyin: 'D' }, ...... ]
2) JSON篇
const FristPin = ["A", "B", "C", "D", "E", "F", "G", "H", "I","J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]; exports.index = async(req, res) => { let citys = await city_service.findAll({}); let cityJson = {}; for (let i = 0; i < FristPin.length; i++) { cityJson[FristPin[i]] = citys.filter(function (value) { return value.firstletter === FristPin[i]; }) }
得到的数据:
{ A: [], B: [], C: [ { cityname: '长沙', firstletter: 'C', id: 1, pinyin: 'changsha' }, { cityname: '常德', firstletter: 'C', id: 2, pinyin: 'changde' } ] }