I feel embarrassed for asking this question as I should know how to figure it out, but I’m spinning my wheels on grouping an array of objects by multiple keys.
Here’s the data:
JavaScript
x
43
43
1
[
2
{
3
"car": "audi",
4
"type": "A6",
5
"style": "Avant",
6
"year": "1996"
7
},
8
{
9
10
"car": "audi",
11
"type": "A4",
12
"style": "2",
13
"year": "2006"
14
},
15
{
16
17
"car": "audi",
18
"type": "A4",
19
"style": "L W12",
20
"year": "2006"
21
},
22
{
23
24
"car": "audi",
25
"type": "80",
26
"style": "GLE",
27
"year": "1975"
28
},
29
{
30
31
"car": "audi",
32
"type": "A6",
33
"style": "Avant L",
34
"year": "1996"
35
},
36
{
37
"car": "audi",
38
"type": "A6",
39
"style": "3.2 Multitronic",
40
"year": "2006"
41
},
42
]
43
What I’ve been trying to generate with little success is the following:
JavaScript
1
14
14
1
[{
2
"audi": [{
3
"1996": {
4
"A6": ["Avant, Avant L"]
5
}
6
}, {
7
"2006": }
8
"A6": ["3.2 Multitronic"],
9
"A4": ["L W12", "2"]
10
}
11
}
12
.
13
}]
14
The schema is:
JavaScript
1
23
23
1
{
2
"car1": [{
3
"year1": {
4
"style1": ["trim1", "trim2"],
5
"style2": ["trim1", "trim2"]
6
},
7
"year1": {
8
"style1": ["trim1", "trim2"],
9
"style2": ["trim1", "trim2"]
10
}
11
}],
12
"car2": [{
13
"year1": {
14
"style1": ["trim1", "trim2"],
15
"style2": ["trim1", "trim2"]
16
},
17
"year2": {
18
"style1": ["trim1", "trim2"],
19
"style2": ["trim1", "trim2"]
20
}
21
}]
22
}
23
I’ve tried the following with lodash
JavaScript
1
8
1
let result = _.chain(carData)
2
.groupBy('car')
3
.toPairs()
4
.map(function(curr) {
5
return _.zipObject(['car', 'year'], curr);
6
})
7
.value();
8
This gets me part of the way, but I end up with incomplete data when it comes to the styles and types for each year of the car.
Advertisement
Answer
You could use a hash object and a nested approach for the given properties.
JavaScript
1
17
17
1
var data = [{ car: "audi", type: "A6", style: "Avant", year: 1996 }, { car: "audi", type: "A4", style: 2, year: 2006 }, { car: "audi", type: "A4", style: "L W12", year: 2006 }, { car: "audi", type: 80, style: "GLE", year: 1975 }, { car: "audi", type: "A6", style: "Avant L", year: 1996 }, { car: "audi", type: "A6", style: "3.2 Multitronic", year: 2006 }],
2
keys = ['car', 'year', 'type'],
3
result = [];
4
5
data.forEach(function (a) {
6
keys.reduce(function (r, k) {
7
var o = {};
8
if (!r[a[k]]) {
9
r[a[k]] = { _: [] };
10
o[a[k]] = r[a[k]]._;
11
r._.push(o);
12
}
13
return r[a[k]];
14
}, this)._.push(a.style);
15
}, { _: result });
16
17
console.log(result);
JavaScript
1
1
1
.as-console-wrapper { max-height: 100% !important; top: 0; }