From API, I get array of attendances by date with members data. My task is to convert that data to array of objects with clients data end attend_date. I managed to accomplish that in following snippet. My plea to You is for hint for other, perhaps more performant or more elegant way for solving my task.
JavaScript
x
31
31
1
const attendances = [
2
{ _id: '1',
3
attend_date: '2020-12-31',
4
members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
5
},
6
{_id: '2',
7
attend_date: '2021-01-01',
8
members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
9
},
10
{_id: '3',
11
attend_date: '2021-01-04',
12
members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
13
}
14
]
15
16
const mapAttendances = () => {
17
let obj,
18
arr = [];
19
for (let i = 0; i < attendances.length; i++) {
20
for (let j = 0; j < attendances[i].members.length; j++) {
21
obj = {
22
date: attendances[i].attend_date,
23
present: attendances[i].members[j].present,
24
client: attendances[i].members[j].client,
25
};
26
arr.push(obj);
27
}
28
}
29
return arr;
30
}
31
console.log(mapAttendances())
Advertisement
Answer
You can also do this with some nested maps and a little destructuring
JavaScript
1
22
22
1
const attendances = [
2
{ _id: '1',
3
attend_date: '2020-12-31',
4
members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
5
},
6
{_id: '2',
7
attend_date: '2021-01-01',
8
members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
9
},
10
{_id: '3',
11
attend_date: '2021-01-04',
12
members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
13
}
14
]
15
16
const mapAttendances = () => {
17
return attendances.flatMap(({attend_date:date, members}) => {
18
return members.map(({_id,r}) => ({ date,r }));
19
});
20
}
21
22
console.log(mapAttendances())