我有两个像这样的javascript数组。
var category = ['Jacket'];
var subcategory = ['Woman', 'Men', 'Kids'];
我希望像这样组合数组值
var finalCategory = ['Jacket Woman', 'Jacket Men', 'Jacket Kids'];
如果类别不止一个,最终结果
var category = ['Jacket', 'Bags'];
var subcategory = ['Woman', 'Men', 'Kids'];
var finalCategory = ['Jacket Woman', 'Jacket Men', 'Jacket Kids', 'Bags Woman', 'Bags Men', 'Bags Kids'];
请帮助,谢谢。
答案 0 :(得分:6)
您可以使用嵌套循环创建cartesian product。
var category = ['Jacket', 'Bags'],
subcategory = ['Woman', 'Men', 'Kids'],
result = category.reduce(function (r, a) { // use an accumulator and item
return r.concat(subcategory.map(function (b) { // concat result of mapped subs
return [a, b].join(' '); // build string with given items
}));
}, []); // take array as accumulator
console.log(result);

ES6
var category = ['Jacket', 'Bags'],
subcategory = ['Woman', 'Men', 'Kids'],
result = category.reduce((r, a) => r.concat(subcategory.map(b => [a, b].join(' '))), []);
console.log(result);

答案 1 :(得分:3)
var category = ['Jacket', 'Bags'];
var subcategory = ['Woman', 'Men', 'Kids'];
var finalCategory = []
for(var i = 0; i < category.length; i++){
for(var ii = 0; ii < subcategory.length; ii++){
finalCategory.push(category[i] + ' ' + subcategory[ii])
}
}
console.log(finalCategory)
嵌套循环。一个涵盖所有主要类别,然后涵盖其中的子类别。
答案 2 :(得分:2)
您可以使用
var category = ['Jacket', 'Bags'];
var subcategory = ['Woman', 'Men', 'Kids'];
var combos = [];
category.forEach(function(a){
subcategory.forEach(function(b){
combos.push(a + ' ' + b);
});
});
答案 3 :(得分:0)
使用嵌套for循环创建一个新数组:
function concatArr(arr1, arr2) {
var newArr = [];
for (var a = 0; a < arr1.length; a++) {
var arr1Value = arr1[a];
for (var b = 0; b < arr2.length; b++) {
var arr2Value = arr2[b];
newArr.push(arr1Value + " " + arr2Value);
}
}
return newArr;
}
//TEST
var category = ['Jacket', 'Pants'];
var subcategory = ['Woman', 'Men', 'Kids'];
console.log(concatArr(category, subcategory));
&#13;