js提取公共的属性

eg:

cityList = [
	{ id: 1, city: '铜陵', province: '安徽' },
	{ id: 2, city: '安庆', province: '安徽' },
	{ id: 3, city: '合肥', province: '安徽' },
	{ id: 4, city: '义乌', province: '浙江' },
	{ id: 5, city: '金华', province: '浙江' }
];

转换方式

let dataInfo = {};
cityList.forEach((item, index) => {
	let { province } = item;
	if (!dataInfo[province]) {
		dataInfo[province] = {
			id: index,
			province,			
			child: []
		}
	}
	dataInfo[province].child.push(item);
});
let list = Object.values(dataInfo); // list 转换成功的数据

输出

 [
	{ id: 0, province: '安徽', child: [
			{ city_id: 1,city_name: '铜陵',province: '安徽'	},
			{ city_id: 2,city_name: '安庆',province: '安徽'	},
			{ city_id: 3,city_name: '合肥',province: '安徽'	}
		]
	},
	{ id: 1, province: '浙江', child: [
			{ city_id: 4, city_name: '义乌', province: '浙江' },
			{ city_id: 5, city_name: '金华', province: '浙江' }
		]
	}
];

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页