我有两个包含2个数组的对象。我想以这样的方式创建循环,即第一个数组的每个元素都连接到第二个数组的每个元素。
{'array1':['a','b'],'array2':['1','2']}
它应该创建新数组
['a,1':{'prop1':""},'a,2':{'prop1':""},'b,1':{'prop1':""}, 'b,2':{'prop1':""}]
如何在javascript中执行此操作。
答案 0 :(得分:2)
您的输出不可用,这不是有效的语法:
["abc": {...}]
您要输出的内容是这样的对象:{"abc": {..}}
您将需要迭代两个数组,一个外部迭代和一个内部迭代:
var input = {'array1':['a','b'],'array2':['1','2']};
var output = {};
// Outer iteration:
// a1 will contain each value from array1 (a, b)
input.array1.forEach(function(a1) {
// Inner iteration:
// a2 will contain each value from array2 (1, 2)
input.array2.forEach(function(a2) {
// Concatenate the to values (`a,1`, `a,2`, `b,1`, `b,2`) and assign the dummy object:
output[a1+','+a2] = { prop1: '' };
});
});
console.log(output); // {"a,1":{"prop1":""},"a,2":{"prop1":""},"b,1":{"prop1":""},"b,2":{"prop1":""}}
答案 1 :(得分:0)
这是一个基于@ dev-null的解决方案构建的函数。这会以您想要的方式重新构建对象,但不依赖于键和#39;名称或对象中的数组数。它应该与任何长度的输入对象一起使用,只要它以相同的方式构造。此外,我确定有一种优化方法,但对于这个例子来说似乎足够快。
var input = {
'array1':['a','b'],
'array2':['1','2', '3'],
'array3':['x','y', 'z']
};
var output = combineObj(input);
console.log(output);
// In: an object of arrays
// Returns restructured object
function combineObj(obj) {
var allVals = [];
var locatoins = [0];
var output = {};
var keys = Object.keys(obj).sort();
var counter = 0;
// combine each individual array into one big array
keys.forEach(function(objItem, indx){
obj[objItem].forEach(function(aryItem){
allVals.push(aryItem);
counter++;
});
locatoins.push(counter);
});
// Used in combination with the locations array to track where a new array begins
// The purpose of this is so items from the same array in input aren't combined
var iterator = 1;
for( i=0; i < allVals.length; i++ ){
if(i == locatoins[iterator]){
iterator++;
}
for( j = 0; j < allVals.length; j++ ){
if( j >= locatoins[iterator-1] && j < locatoins[iterator] ){
continue;
}
output[allVals[i] + ', ' + allVals[j]] = { prop1: '' };
}
}
return output;
}