js中数据分类整理技巧

  • 将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)
  • 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"
			}
		]
	}
]
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值