我有一个以下形式的对象(下面是简化的测试案例)
var test = {
shirts: {
sizes: ['large', 'medium']
,colors:['red', 'blue']
}
, trousers: {
type: ['formal', 'casual']
, pattern: ['plaid', 'stripes']
}
};
我希望生成属性的笛卡尔积,使输出为以下形式的数组:
// desired output
[ {shirts:{sizes:'large', color:'red'}, trousers:{type:'formal', pattern:'plaid'}}
,{shirts:{sizes:'large', color:'red'}, trousers:{type:'formal', pattern:'stripes'}}
,{shirts:{sizes:'large', color:'red'}, trousers:{type:'casual', pattern:'plaid'}}
, {shirts:{sizes:'large', color:'red'}, trousers:{type:'casual', pattern:'stripes'}}
,{shirts:{sizes:'large', color:'blue'}, trousers:{type:'formal', pattern:'plaid'}}
..... and so on ]
我该如何实现这一点?我根据另一个SO帖子上的数组笛卡尔积修改了以下代码,但似乎陷入了纠结之中,试图让其正常运行。
function myCartesianProduct(input, current) {
if (!input) { return []; }
var head = input[Object.keys(input)[0]];
var tail = objSlice(input);
var output = [];
for (var key in head) {
for (var i = 0; i < head[key].length; i++) {
var newCurrent = copy(current);
newCurrent[key] = head[key][i];
if (Object.keys(tail).length) { //if tail.length
var productOfTail =
myCartesianProduct(tail, newCurrent);
output = output.concat(productOfTail);
} else {
output.push(newCurrent);
}
}
}
return output;
}
function objSlice(obj) {
var slicedObj = angular.copy(obj); // copy object using angularJs copy method
delete slicedObj[Object.keys(slicedObj)[0]]; //delete the first key
return slicedObj;
};
function copy(obj) {
var res = {};
for (var p in obj) res[p] = obj[p];
return res;
}
console.log(myCartesianProduct(test));
Thanks in advance for your help with this!
map
函数。 - Paul