JavaScript-从字典键生成组合并动态保留键名 [英] JavaScript - Generating combinations from dictionary keys and keeping key names dynamically
问题描述
我发现这个出色的代码可以在这里生成多个arrays
的所有组合:
I found this excellent code which generates all the combinations of multiple arrays
here: JavaScript - Generating combinations from n arrays with m elements
我现在想更进一步,我想生成许多包含arrays
的JSON
对象的所有组合
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
推荐答案
您可以将对象数组转换为多维数组.构建可能的组合,并使用map
构建最终格式.
You can convert the array of objects into multi dimensional array. Construct possible combinations and use map
to construct the final format.
var arr = [{"Footprint_Shape": ["L-Shape", "H-Shape", "T-Shape"]}, {"Num_of_Floors": [1, 2]}];
var result = arr.map(o => Object.values(o)[0]) //Convert the array of objects into multi dimensional array.
.reduce((c, v) => [].concat(...c.map(o => v.map(x => [].concat(o, x))))) //Make all possible combinations
.map(([a, b]) => ({"Footprint_Shape": a,"Num_of_Floors": b})) //Construct the final format
console.log(result);
更新:
var arr = [{"Footprint_Shape": ["L-Shape", "H-Shape", "T-Shape"]}, {"Num_of_Floors": [1, 2]}];
var keys = arr.map(o => Object.keys(o)[0]); //Get the list of keys
var result = arr.map(o => Object.values(o)[0]) //Convert the array of objects into multi dimensional array.
.reduce((c, v) => [].concat(...c.map(o => v.map(x => [].concat(o, x))))) //Make all possible combinations
.map(o => o.reduce((c, v, i) => Object.assign(c, {[keys[i]]: v}), {})); //Construct the final format
console.log(result);
这篇关于JavaScript-从字典键生成组合并动态保留键名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!