原数据:
[
{ city_id: 1, city_name: '南京', province: '江苏' },
{ city_id: 2, city_name: '苏州', province: '江苏' },
{ city_id: 3, city_name: '淮安', province: '江苏' },
{ city_id: 4, city_name: '杭州', province: '浙江' },
{ city_id: 5, city_name: '金华', province: '浙江' }
];
目标数据:
[
{ 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: '浙江' }
]
}
];
实现方法,话不多说,直接上代码,各位大佬有更好的解决方案,欢迎留言!!!
let dataInfo = {};
data.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 转换成功的数据