我发现了这个优秀的代码,它在这里生成多个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 }]请记住,我需要动态生成所有的键和值。
任何指针或代码示例,如果能为我指出编写这段代码的正确方向,我们将不胜感激。
发布于 2018-06-20 03:46:57
您可以将对象数组转换为多维数组。构造可能的组合并使用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);
发布于 2018-06-20 10:55:25
一个简单而简短的备选方案:
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);发布于 2018-06-20 03:52:42
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)
我认为代码应该是不言自明的。使用两个循环,构造对象并推送到一个新数组。
https://stackoverflow.com/questions/50939817
复制相似问题