我思考并搜索了很多,但找不到答案:
我需要编写一个 js 函数来获取一个具有未知数量数组的对象,该对象又具有未知数量的元素。就像这样:
{
Color: ["Color : Red", "Color : Blue", "Color : Green"],
Size : ["Size : S", "Size : M", "Size : L"],
Material : ["Material : Cotton"],
Something : ["Something : Anything", "Something : Anotherthing"]
}
同样,这可能是更多(或更少)的数组和元素,但在这种情况下,我希望实现这样的输出:
{0: "Color : Red > Size : S > Material : Cotton > Something : Anything",
1: "Color : Red > Size : S > Material : Cotton > Something : Anotherthing",
2: "Color : Red > Size : M > Material : Cotton > Something : Anything",
3: "Color : Red > Size : M > Material : Cotton > Something : Anotherthing",
4: "Color : Red > Size : L > Material : Cotton > Something : Anything",
5: "Color : Red > Size : L > Material : Cotton > Something : Anotherthing",
6: "Color : Blue > Size : S > Material : Cotton > Something : Anything",
...
...[and so forth... ]}
我尝试在循环中循环,但失败了。 然后我尝试首先找到最长的数组,从其余数组中提取它,然后循环遍历每个数组以获取最长的每个元素:
createMap = function(tagObj, longest){
var longObj = tagObj[longest];
var current = {};
delete tagObj[longest];
$.each(tagObj, function(name, obj){
$.each(obj, function(index, tag){
$.each(longObj, function(i, iniTag){
if (current[i]!= undefined){
current[i] += " > " + tag;
}
else current[i] = iniTag + " > " + tag;
})
})
})
console.log(current);
}
但这只会导致:
{0: "Color : Red, Size : S, Size : M, Size : L, .... "}
我希望我不只是忽略了一些非常明显的事情 - 但我花了太多时间在上面,只是无法弄清楚。现在我神经衰弱,无法再正常思考。 我非常感谢一些帮助!提前致谢!
最佳答案
您可以为此使用简单的递归解决方案:
function combine( obj ) {
var keys = Object.keys(obj), combinations = [];
// keys.sort(); // optional
function rc(ki, combo) {
var list;
if (ki === keys.length)
combinations.push(combo);
else {
list = obj[ keys[ki] ];
for (var i = 0; i < list.length; ++i)
rc( ki + 1, combo + " " + list[i] );
}
}
rc(0, '');
return combinations;
}
它以起始对象的键列表和一个空结果数组开始。请注意,对键进行排序以便以可预测的顺序返回结果可能是明智的,因为属性名称列表没有定义的顺序。
递归“rc”函数从键数组中的特定索引开始。对于数组中与该键关联的每个字符串,该函数递归地调用自身以对 next 键进行操作,并通过将列表元素附加到传入的字符串末尾而形成一个基本字符串。键列表已用尽,每个完成的组合字符串都将附加到结果列表中。
通过调用第零个键的“rc”和空字符串作为起始值来启动该过程。
关于javascript - 如何获取未知数量数组中未知数量元素的所有组合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21913732/