我有一个数组
{
"id": 5308,
"empId": 202,
"loc": 1,
"salMonth": "1",
"salYear": "2020",
"salDate": "2020-01",
"netSal": 50000
},
{
"id": 5309,
"empId": 173,
"loc": 1,
"salMonth": "1",
"salYear": "2020",
"salDate": "2020-01",
"netSal": 30000
},
{
"id": 5310,
"empId": 212,
"loc": 1,
"salMonth": "1",
"salYear": "2020",
"salDate": "2020-01",
"netSal": 21100
},
{
"id": 5311,
"empId": 163,
"loc": 1,
"salMonth": "1",
"salYear": "2020",
"salDate": "2020-01",
"netSal": 43000
},
{
"id": 5312,
"empId": 116,
"loc": 1,
"salMonth": "1",
"salYear": "2020",
"salDate": "2020-01",
"netSal": 52000
},
{
"id": 5313,
"empId": 223,
"loc": 1,
"salMonth": "1",
"salYear": "2020",
"salDate": "2020-01",
"netSal": 21100
},
{
"id": 5314,
"empId": 231,
"loc": 1,
"salMonth": "1",
"salYear": "2020",
"salDate": "2020-01",
"netSal": 42217
}
我必须将这个数组按两列分组,即empId, salDate。
预期的结果应该是:
{
"202": {
"2020-01": {
"salId": xx,
"salary": xxx
},
"2020-02": {
"salId": xxx,
"salary": xxxx
},
"2020-03": {
"salId": xxx,
"salary": xxxx
}
},
"203": {
"2020-01": {
"salId": xx,
"salary": xxx
},
"2020-02": {
"salId": xxx,
"salary": xxxx
},
"2020-03": {
"salId": xxx,
"salary": xxxx
}
},
}
谢谢 ............................................................................................................................................................................................................................................................................
一个简单的循环可以解决您的问题。试试这个。
let modifiedData = {}
let data = [{
"id": 5308,
"empId": 202,
"loc": 1,
"salMonth": "1",
"salYear": "2020",
"salDate": "2020-01",
"netSal": 50000
},
{
"id": 5309,
"empId": 173,
"loc": 1,
"salMonth": "1",
"salYear": "2020",
"salDate": "2020-01",
"netSal": 30000
},
{
"id": 5310,
"empId": 212,
"loc": 1,
"salMonth": "1",
"salYear": "2020",
"salDate": "2020-01",
"netSal": 21100
}
];
//loop your data and create modifed data
data.map(d => {
if(!modifiedData[d.empId]) { // check weather empId already exists or not
modifiedData[d.empId] = []
}
modifiedData[d.empId].push({[d.salDate]:{salId: d.id, salary: d.netSal}})
})
console.log(modifiedData) // print final data