把扁平数据处理成三级数据
时间: 2023-05-26 16:05:51 浏览: 69
假设我们有以下的扁平数据:
```
[
{
"id": "1",
"name": "John",
"department": "IT",
"salary": "5000"
},
{
"id": "2",
"name": "Lisa",
"department": "HR",
"salary": "6000"
},
{
"id": "3",
"name": "Tom",
"department": "IT",
"salary": "4500"
},
{
"id": "4",
"name": "Anne",
"department": "Finance",
"salary": "7000"
}
]
```
我们可以使用以下代码将其处理成三级数据:
```
var data = [
{
"id": "1",
"name": "John",
"department": "IT",
"salary": "5000"
},
{
"id": "2",
"name": "Lisa",
"department": "HR",
"salary": "6000"
},
{
"id": "3",
"name": "Tom",
"department": "IT",
"salary": "4500"
},
{
"id": "4",
"name": "Anne",
"department": "Finance",
"salary": "7000"
}
];
// 第一级数据(部门)
var departments = {};
for (var i = 0; i < data.length; i++) {
var entry = data[i];
if (!(entry.department in departments)) {
departments[entry.department] = [];
}
departments[entry.department].push(entry);
}
// 第二级数据(员工)
var employees = {};
for (var department in departments) {
employees[department] = {};
for (var i = 0; i < departments[department].length; i++) {
var entry = departments[department][i];
employees[department][entry.id] = entry;
}
}
// 第三级数据(薪资)
var salaries = {};
for (var department in employees) {
salaries[department] = {};
for (var id in employees[department]) {
var entry = employees[department][id];
salaries[department][id] = entry.salary;
}
}
console.log(salaries);
```
输出结果为:
```
{
"IT": {
"1": "5000",
"3": "4500"
},
"HR": {
"2": "6000"
},
"Finance": {
"4": "7000"
}
}
```
可以看到,我们已经成功地将扁平数据处理成了三级数据。第一级数据是部门,第二级数据是员工,第三级数据是薪资。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)