JavaScript-从字典键生成组合并动态保留键名

时间:2018-06-20 03:36:19

标签: javascript algorithm dictionary combinations permutation

我发现这个出色的代码可以在这里生成多个arrays的所有组合:JavaScript - Generating combinations from n arrays with m elements

我现在想更进一步,我想生成包含JSON的多个arrays对象的所有组合

例如,如果我在下面看到的数组中有两个对象:

[{"Footprint_Shape":["L-Shape","H-Shape","T-Shape"]},
{"Num_of_Floors":[1,2]}]

我想在保持键的同时生成下面的数组,该数组是每个组合:

    [{"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 }]

请记住,我需要动态生成所有键和值。

任何会向我指出正确方向编写此代码的指针或代码示例,将是最感激的

3 个答案:

答案 0 :(得分:1)

您可以将对象数组转换为多维数组。构建可能的组合,并使用map构建最终格式。

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);

答案 1 :(得分:1)

一个简单而简短的选择:

const [{Footprint_Shape: shapes},{Num_of_Floors: floors} ] = [{"Footprint_Shape":["L-Shape","H-Shape","T-Shape"]},{"Num_of_Floors":[1,2]}];

const result = floors.reduce((all, floor) => {

    shapes.forEach(shape => all.push({Footprint_Shape: shape, Num_of_Floors: floor}))

    return all;

}, []);

console.log(result);

答案 2 :(得分:0)

let arr = [
  {"Footprint_Shape":["L-Shape","H-Shape","T-Shape"]},
  {"Num_of_Floors":[1,2]}
]

let answer = [];

arr[0]["Footprint_Shape"].forEach(x => {  
  
  arr[1]["Num_of_Floors"].forEach(y => {
    
    let newObj = {};  
    newObj["Footprint_Shape"] = x;
    //console.log('y: ',y)
    newObj["Num_of_Floors"] = y
  	answer.push(newObj);
    
  })
});

console.log(answer)

我认为代码应该是自我解释的。使用两个循环,构造对象并推送到新数组