扁平数据如何处理。

后台给到一个数组,数组里面全部都是对象,然后需要把一类的数据归为一类。

用一个新数组,装一个个对象,对象里面有label,id,children。
children就是装 同一类型的对象的。

方法:
第一遍遍历res.data,把同一类的id,label,或者xx,安装到对象里面。

然后再拿这个新数组,和res.data双层遍历一下,把res.data里面符合条件的对象,添加到对象里面的children里面。

假设我们有以下的扁平数据: ``` [ { "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" } } ``` 可以看到,我们已经成功地将扁平数据处理成了三级数据。第一级数据是部门,第二级数据是员工,第三级数据是薪资。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值