I found this excellent code which generates all the combinations of multiple arrays
here: JavaScript - Generating combinations from n arrays with m elements
I am now looking to go a step further and I would like to generate all the combinations of a number of JSON
objects containing arrays
For example if I have the two objects within an array seen below:
[{"Footprint_Shape":["L-Shape","H-Shape","T-Shape"]},
{"Num_of_Floors":[1,2]}]
I would like to produce the array below which is every combination while keeping the keys:
[{"Footprint_Shape": "L-Shape", "Num_of_Floors":1 },
{ "Footprint_Shape": "H-Shape", "Num_of_Floors":1 },
{ "Footprint_Shape": "T-Shape", "Num_of_Floors":1 },
{ "Footprint_Shape": "L-Shape", "Num_of_Floors":2 },
{ "Footprint_Shape": "H-Shape", "Num_of_Floors":2 },
{ "Footprint_Shape": "T-Shape", "Num_of_Floors":2 }]
Please remember that I need to generate all keys and values dynamically.
Any pointers or code samples which would point me in the right direction to write this code would be most appreciated
I think the code should be self explanatory. Using two looping, construct the object and push to a new array
You can convert the array of objects into multi dimensional array. Construct possible combinations and use
map
to construct the final format.Update:
A simple and short alternative: