I have been working on a Cartesian product with a below array of objects.
[
{
"name": "Size",
"values": ["10", "39"]
},
{
"name": "Color",
"values": ["Yellow", "Pink"]
},
{
"name": "Country",
"values": ["USA", "UK"]
}
]
And I want to generate a cartesian product of the properties so that the output is an array of the following form:
[
[
{ id: 1, name: 'Size', value: '10' },
{ id: 2, name: 'Color', value: 'Yellow' },
{ id: 3, name: 'Country', value: 'USA' },
],
[
{ id: 1, name: 'Size', value: '10' },
{ id: 2, name: 'Color', value: 'Yellow' },
{ id: 3, name: 'Country', value: 'UK' },
],
[
{ id: 1, name: 'Size', value: '39' },
{ id: 2, name: 'Color', value: 'Yellow' },
{ id: 3, name: 'Country', value: 'USA' },
],
[
{ id: 1, name: 'Size', value: '39' },
{ id: 2, name: 'Color', value: 'Yellow' },
{ id: 3, name: 'Country', value: 'UK' },
],
[
{ id: 1, name: 'Size', value: '10' },
{ id: 2, name: 'Color', value: 'Pink' },
{ id: 3, name: 'Country', value: 'USA' },
],
[
{ id: 1, name: 'Size', value: '10' },
{ id: 2, name: 'Color', value: 'Pink' },
{ id: 3, name: 'Country', value: 'UK' },
],
[
{ id: 1, name: 'Size', value: '39' },
{ id: 2, name: 'Color', value: 'Pink' },
{ id: 3, name: 'Country', value: 'USA' },
],
[
{ id: 1, name: 'Size', value: '39' },
{ id: 2, name: 'Color', value: 'Pink' },
{ id: 3, name: 'Country', value: 'UK' },
],
];
2
Answers
Here’s one concise way to do this with recursion:
Output:
here is a non-recursive solution based on a previous answer