var arr = [ { date: "5月15号", id: 1 }, { date: "5月15号", id: 2 }, { date: "5月15号", id: 3 }, { date: "5月15号", id: 4 }, { date: "5月18号", id: 5 }, { date: "5月18号", id: 6 }, { date: "5月18号", id: 7 }, { date: "5月18号", id: 8 }, { date: "4月1号", id: 9 }, { date: "4月1号", id: 10 }, { date: "4月1号", id: 11 }, ]要转成// var obj = { // "5月15号" : [ { date:"5月15号" , id:1 }, // { date:"5月15号" , id:2 }, // { date:"5月15号" , id:3 }, // { date:"5月15号" , id:4 },], // "5月18号":[ { date:"5月18号" , id:5 }, // { date:"5月18号" , id:6 }, // { date:"5月18号" , id:7 }, // { date:"5月18号" , id:8 },], // "4月1号":[ { date:"4月1号" , id:9 }, // { date:"4月1号" , id:10 }, // { date:"4月1号" , id:11 }] // }
时间: 2024-02-20 20:57:49 浏览: 24
可以通过遍历数组并使用对象来存储转换后的数据来达到目标。以下是实现的代码:
```
var arr = [
{ date: "5月15号", id: 1 },
{ date: "5月15号", id: 2 },
{ date: "5月15号", id: 3 },
{ date: "5月15号", id: 4 },
{ date: "5月18号", id: 5 },
{ date: "5月18号", id: 6 },
{ date: "5月18号", id: 7 },
{ date: "5月18号", id: 8 },
{ date: "4月1号", id: 9 },
{ date: "4月1号", id: 10 },
{ date: "4月1号", id: 11 },
];
var obj = {};
for(var i = 0; i < arr.length; i++) {
var item = arr[i];
if(obj[item.date]) {
obj[item.date].push(item);
} else {
obj[item.date] = [item];
}
}
console.log(obj);
```
输出:
```
{
"5月15号": [
{ date: "5月15号", id: 1 },
{ date: "5月15号", id: 2 },
{ date: "5月15号", id: 3 },
{ date: "5月15号", id: 4 }
],
"5月18号": [
{ date: "5月18号", id: 5 },
{ date: "5月18号", id: 6 },
{ date: "5月18号", id: 7 },
{ date: "5月18号", id: 8 }
],
"4月1号": [
{ date: "4月1号", id: 9 },
{ date: "4月1号", id: 10 },
{ date: "4月1号", id: 11 }
]
}
```
这样就将原始数组转换为了目标对象。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)