I have this:
JavaScript
x
16
16
1
products = [
2
{
3
'id': 1
4
'name: 'test'
5
},
6
{
7
'id': 2
8
'name: 'test'
9
},
10
{
11
'id': 3
12
'name: 'test'
13
}
14
etc, etc
15
]
16
I need to restructure it to this:
JavaScript
1
40
40
1
products = [
2
row1: [
3
{
4
'id': 1
5
'name: 'test'
6
},
7
{
8
'id': 2
9
'name: 'test'
10
},
11
{
12
'id': 3
13
'name: 'test'
14
},
15
{
16
'id': 4
17
'name: 'test'
18
}
19
]
20
row2: [
21
{
22
'id': 5
23
'name: 'test'
24
},
25
{
26
'id': 6
27
'name: 'test'
28
},
29
{
30
'id': 7
31
'name: 'test'
32
},
33
{
34
'id': 8
35
'name: 'test'
36
}
37
]
38
row3: [.. etc, etc
39
]
40
the hard part is that the number of objects in each group is set using a variable (in this example the variable would be 4).
How can I achieve this using Typescript/Javascript? Its driving me mad!
Thanks
Advertisement
Answer
Use Array.reduce()
You can run a .reduce() method on your products array, like so:
JavaScript
1
19
19
1
var products = [
2
{ 'id': 1, name: 'test' },
3
{ 'id': 2, name: 'test' },
4
{ 'id': 3, name: 'test' },
5
{ 'id': 4, name: 'test' },
6
{ 'id': 5, name: 'test' },
7
{ 'id': 6, name: 'test' }
8
]
9
10
var numberOfObjects = 4 // <-- decides number of objects in each group
11
12
var groupedProducts = products.reduce((acc, elem, index) => {
13
var rowNum = Math.floor(index/numberOfObjects) + 1
14
acc[`row${rowNum}`] = acc[`row${rowNum}`] || []
15
acc[`row${rowNum}`].push(elem)
16
return acc
17
}, {})
18
19
console.log(groupedProducts)