- 将oldData中的数据按照国家分类成一个新的列表,其中包含name和cities字段,cities中存放对应的城市列表。
- 直接上代码,利用Map中key的唯一性分类(此处直接用js对象作为Map使用):
const oldData = [
{
city_id:1,
city_name:'北京',
city_img:"http://dfknbdjknvkjsfnvlkjdn.png",
city_country:"中国"
},
{
city_id:2,
city_name:'上海',
city_img:"http://wergerbe.png",
city_country:"中国"
},
{
city_id:3,
city_name:'广州',
city_img: "http://hrthhr.png",
city_country:"中国"
},
{
city_id:4,
city_name:'西雅图',
city_img:"http://frevfd.png",
city_country:"美国"
},
{
city_id:5,
city_name:'纽约',
city_img:"http://guifdhoudhoss.png",
city_country:"美国"
}
];
console.log("oldData:",oldData)
const classifyMap = {}, newData=[];
for(let item of oldData){
const country = item.city_country;
delete item.city_country;
const countryItem = classifyMap[country];
if(countryItem){
countryItem.cities.push(item);
}else{
classifyMap[country] = {
name: country,
cities: [item]
}
}
}
for(let name in classifyMap){
newData.push(classifyMap[name]);
}
console.log("newData:",newData)
[
{
"name":"中国",
"cities":[
{
"city_id":1,
"city_name":"北京",
"city_img":"http://dfknbdjknvkjsfnvlkjdn.png"
},
{
"city_id":2,
"city_name":"上海",
"city_img":"http://wergerbe.png"
},
{
"city_id":3,
"city_name":"广州",
"city_img":"http://hrthhr.png"
}
]
},
{
"name":"美国",
"cities":[
{
"city_id":4,
"city_name":"西雅图",
"city_img":"http://frevfd.png"
},
{
"city_id":5,
"city_name":"纽约",
"city_img":"http://guifdhoudhoss.png"
}
]
}
]