1.场景一: 人员选择相关问题
/* 场景一:从人员选择数据中,提取已选的人员信息
selectedList为已选择的人员信息,只有id
groupInfo接口返回的原始数据,所有人员信息
需要找出已选择的人员信息的具体信息,
*/
const groupInfo =[
{userId:'kebi',userName:'科比',age:33,phone:199},
{userId:'maidi',userName:'麦迪',age:35,phone:188},
{userId:'ai',userName:'艾弗森',age:38,phone:166},
]
const selectedList = ['kebi','maidi']
const _selectedList = []
selectedList.map((id) => { // 1.从已知的数组开始循环
const userInfo = groupInfo.find((item) => { // 2.在原始数据里找,有的话放到新的数组里
return item.userId === id
})
// 箭头函数,只有一行代码,return和花括号可以一起省略
// const userInfo = groupInfo.find(({ userId }) => userId === id )
if(userInfo) _selectedList.push(userInfo)
})
console.log(_selectedList)
2.场景二: 从配置化列表选择数据
/* 场景二:从配置话数据里寻找所需数据
需要找的字段没有在一个数组里,而是放在了一个对象里
需要找出对象里有值的字段的信息,
*/
let person = {
name:'kebi',
sex:'',
age:'',
city:'xian',
prv:'陕西'
}
let conf = [
{keys:'name',lable:"姓名",num:23},
{keys:'xian',lable:"西安",num:29},
{keys:'beijing',lable:"北京",num:20}
]
/*
conf为配置对象,数组格式
1.先找出对象中不为空的数据,组成一个数组
2.遍历这个数组,从conf找出这个key对应的项赋值给obj
3.定义一个新数组list2,接受这个obj并新增属性value
*/
let list = []
for(let k in person) {
if(person[k]) {
list.push(k)
}
}
console.log(list,'list')
let list2 = []
list.forEach( item => {
let obj = conf.find( itt => { return itt.keys === item })
if (!obj) return;
let itemInfo = {
...obj,
value:person[item]
}
list2.push(itemInfo)
})
console.log(list2)
3.场景三: 城市选择(移动端)
把数据处理为分类的数据和带索引的数据, 分类的数据不关心顺序,索引数据顺序要正确
接口返回的数据格式:
[{ “label”: “北京”, “value”: “”, “pinyin”: “beijing”, “short”: “bj” }]
渲染城市列表的数据格式为:
{ a: [{}, {}], b: [{}, …] }
渲染右侧索引的数据格式:
[‘a’, ‘b’]
/*
// 接口返回的数据格式:
[{ "label": "北京", "value": "", "pinyin": "beijing", "short": "bj" }]
// 渲染城市列表的数据格式为:
{ a: [{}, {}], b: [{}, ...] }
// 渲染右侧索引的数据格式:
['a', 'b']
*/
// 数据格式化的方法
// 把数据处理为分类的数据和带索引的数据, 分类的数据不关心顺序,索引数据顺序要正确
// list: [{}, {}]
const formatCityData = list => {
const cityList = {}
// const cityIndex = []
// 1 遍历list数组
list.forEach(item => {
// 2 获取每一个城市的首字母
const first = item.short.substr(0, 1)
// 3 判断 cityList 中是否有该分类
if (cityList[first]) {
// 4 如果有,直接往该分类中push数据
// cityList[first] => [{}, {}]
cityList[first].push(item)
} else {
// 5 如果没有,就先创建一个数组,然后,把当前城市信息添加到数组中
cityList[first] = [item]
}
})
// 获取索引数据
const cityIndex = Object.keys(cityList).sort()
return {
cityList,
cityIndex
}
}
// 获取城市列表数据的方法
async getCityList() {
const res = await axios.get('http://localhost:8080/area/city?level=1')
// console.log('城市列表数据:', res)
const { cityList, cityIndex } = formatCityData(res.data.body)
/*
1 获取热门城市数据
2 将数据添加到 cityList 中
3 将索引添加到 cityIndex 中
*/
const hotRes = await axios.get('http://localhost:8080/area/hot')
// console.log('热门城市数据:', hotRes)
cityList['hot'] = hotRes.data.body
// 将索引添加到 cityIndex 中
cityIndex.unshift('hot')
// 获取当前定位城市
const curCity = await getCurrentCity()
/*
1 将当前定位城市数据添加到 cityList 中
2 将当前定位城市的索引添加到 cityIndex 中
*/
cityList['#'] = [curCity]
cityIndex.unshift('#')
console.log(cityList, cityIndex, curCity)
}