I have an object like this:
JavaScript
x
12
12
1
const object = {
2
detectors: [1, 2],
3
responders: [4, 22],
4
activators: [5, 23, 31],
5
enablers: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
6
upgraders: [14, 15, 16, 17, 18, 19, 20, 21, 22],
7
catalyzer: [12, 29],
8
chains: [27],
9
trappers: [13],
10
finishers: [16],
11
}
12
Expected output :
JavaScript
1
36
36
1
[
2
{
3
'detectors': 1,
4
'responders': 4,
5
'activators': 5,
6
'enablers': 1,
7
'upgraders': 23,
8
'catalyzer': 12,
9
'chains': 27,
10
'trappers': 13,
11
'finishers': 16,
12
},
13
{
14
'detectors': 2,
15
'responders': 4,
16
'activators': 5,
17
'enablers': 1,
18
'upgraders': 23,
19
'catalyzer': 12,
20
'chains': 27,
21
'trappers': 13,
22
'finishers': 16,
23
},
24
{
25
'detectors': 1,
26
'responders': 22,
27
'activators': 5,
28
'enablers': 1,
29
'upgraders': 23,
30
'catalyzer': 12,
31
'chains': 27,
32
'trappers': 13,
33
'finishers': 16,
34
},
35
{
36
And I already wrote a function like this:
JavaScript
1
12
12
1
object.activators.map((activator, i) => {
2
return object.detectors.map((detector, i) => {
3
return object.responders.map((responder, i) => {
4
return {
5
detectors: detector,
6
responders: responder,
7
activators: activator,
8
};
9
});
10
});
11
});
12
I can write another function to flatten the output of the code above, but is there any other way to write the code above into a more general function (not hardcoded) that can apply to any object?
Advertisement
Answer
You can use a recursive function to get all permutations from the entries.
JavaScript
1
20
20
1
const object = {
2
detectors: [1, 2, 3],
3
responders: [4, 22],
4
activators: [1, 2, 3, 4]
5
};
6
const getPermutations = obj => {
7
const res = [];
8
const entries = Object.entries(obj);
9
const go = (curr, idx) => {
10
const key = entries[idx][0];
11
for(const val of entries[idx][1]){
12
const next = {curr, [key]: val};
13
if(idx !== entries.length - 1) go(next, idx + 1);
14
else res.push(next);
15
}
16
};
17
go({}, 0);
18
return res;
19
}
20
console.log(getPermutations(object));