JS合并数组对象中key相同的数据原数据:
[
{ 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]) {js合并两个数组
dataInfo[province] = {
id: index,
province,
child: []
}
}
dataInfo[province].child.push(item);
});
let list = Object.values(dataInfo); // list 转换成功的数据

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。