如何把数组对象处理为{ 浙江: ['杭州', '宁波', '温州', '嘉兴', '湖州'], 福建: ['福州', '厦门', '莆田', '三明', '泉州'], };
时间: 2023-10-23 14:11:33 浏览: 100
java对象转成byte数组的3种方法
假设数组对象为:
```
const cities = [
{ province: '浙江', city: '杭州' },
{ province: '浙江', city: '宁波' },
{ province: '浙江', city: '温州' },
{ province: '浙江', city: '嘉兴' },
{ province: '浙江', city: '湖州' },
{ province: '福建', city: '福州' },
{ province: '福建', city: '厦门' },
{ province: '福建', city: '莆田' },
{ province: '福建', city: '三明' },
{ province: '福建', city: '泉州' },
];
```
可以使用 reduce 方法进行处理:
```
const result = cities.reduce((acc, cur) => {
if (!acc[cur.province]) {
acc[cur.province] = [cur.city];
} else {
acc[cur.province].push(cur.city);
}
return acc;
}, {});
```
最终得到的结果为:
```
{
"浙江": ["杭州", "宁波", "温州", "嘉兴", "湖州"],
"福建": ["福州", "厦门", "莆田", "三明", "泉州"]
}
```
阅读全文