JavaScript更改属性名称+增加字段+排序
- 背景
客户提供的接口里包含了一堆数据,其中分为多个模块,需要进行拆分,其中涉及到名称更改、字段增加、排序。 - 处理过程
-需要的数据:
data: {"四年级": [{ "class": "一班", "number": 29 },{ "class": "叁班", "number": 36 },{ "class": "肆班", "number": 24 },{ "class": "二班", "number": 21 }]
}```
-原始数据:
(1)只要四年级的数据。
(2)将class字段换成grade,并将属性值里的年级去掉只显示班级。
(3)班级中“四”换成“肆”,“三”换成“叁”。
(4)只要一、二、三、四班的数据且按顺序输出。
data: {"年级": [{ "class": "六年一班", "number": 21 },{ "class": "六年三班", "number": 24 },{ "class": "六年四班", "number": 36 },{ "class": "六年二班", "number": 29 },{ "class": "六年五班", "number": 28 },{ "class": "四年一班", "number": 29 },{ "class": "四年三班", "number": 36 },{ "class": "四年四班", "number": 24 },{ "class": "四年二班", "number": 21 },{ "class": "四年五班", "number": 28 },{ "class": "四年六班", "number": 27 },{ "class": "五年一班", "number": 22 },{ "class": "五年三班", "number": 21 },{ "class": "五年四班", "number": 29 },{ "class": "五年二班", "number": 29 },{ "class": "五年五班", "number": 28 }]
}
-处理
function filter(data, callbackArgs) {let filteredMessages = data["年级"].filter(msg => ['四年一班', '四年二班', '四年三班', '四年四班'].includes(msg.class));filteredMessages.forEach(person => {if (person.class === "四年一班") {person.class = "一班"} else if (person.class === "四年二班") {person.class = "二班"} else if (person.class === "四年三班") {person.class = "叁班"} else if (person.class === "四年四班") {person.class = "肆班"}});filteredMessages.sort((a, b) => {const order = ["一班", "二班", "叁班", "肆班"];return order.indexOf(a.class) - order.indexOf(b.class);})var value = new Object();value["四年级"] = filteredMessages;return value;
}