我需要帮助弄清楚如何循环源对象以获取输出字符串。我目前有一些嵌套for循环,但我最终错过了其中一个组合,或者我得到了太多。类别和过滤器的数量会有所不同
源对象
var Source = {Cat1:{Filter1:'f1',Filter2:'f2'},
Cat2:{Filter3:'f3',Filter4:'f4'},
Cat3:{Filter5:'f5'}};
输出字符串
Filter1 Filter3 Filter5,
Filter1 Filter4 Filter5,
Filter2 Filter3 Filter5,
Filter2 Filter4 Filter5
答案 0 :(得分:1)
试试这个,这将返回数组数组:
function cartesianProduct(paramArray) {
function addTo(curr, args) {
var i, copy,
rest = args.slice(1),
last = !rest.length,
result = [];
for (i = 0; i < args[0].length; i++) {
copy = curr.slice();
copy.push(args[0][i]);
if (last) {
result.push(copy);
} else {
result = result.concat(addTo(copy, rest));
}
}
return result;
}
return addTo([], Array.prototype.slice.call(arguments));
};
var Source = {Cat1:{Filter1:'f1',Filter2:'f2'},
Cat2:{Filter3:'f3',Filter4:'f4'},
Cat3:{Filter5:'f5'}};
// var cats = [];
var filters = [];
for(var c in Source) {
filters.push([]);
for(var f in Source[c])
filters[filters.length - 1].push(f);
}
console.log(cartesianProduct.apply(this || window, filters));
HTH