用JavaScript乘2个数组

时间:2019-02-07 20:10:53

标签: javascript arrays reactjs ecmascript-6 javascript-objects

我有2个数组

array1 = ["a","b"]
array2 = [ ["1","2","3"],["10","11","12"]]

我想要的输出是对象数组

[
 {array1: a , array2: 1},
 {array1: a , array2: 2},
 {array1: a , array2: 3},

 {array1: b , array2: 10},
 {array1: b , array2: 11},
 {array1: b , array2: 12},
]

是否有一种简洁的方法来实现此输出而不是嵌套循环

5 个答案:

答案 0 :(得分:2)

似乎您只需要两个循环。有很多方法可以做到这一点。一种简洁的方法是将reduce array1map array2放入外部循环中的结果:

let array1 = ["a","b"]
let array2 = [ ["1","2","3"],["10","11","12"]]

let res = array1.reduce((arr, array1, i) => 
  arr.concat(array2[i].map(array2 => ({array1, array2})))
, [])

console.log(res)

答案 1 :(得分:1)

您可以缩小数组,并获得每个数组的外部元素的笛卡尔积。

function getCartesian(object) {
    return Object.entries(object).reduce((r, [k, v]) => {
        var temp = [];
        r.forEach(s =>
            (Array.isArray(v) ? v : [v]).forEach(w =>
                (w && typeof w === 'object' ? getCartesian(w) : [w]).forEach(x =>
                    temp.push(Object.assign({}, s, { [k]: x }))
                )
            )
        );
        return temp;
    }, [{}]);
}

var array1 = ["a", "b"],
    array2 = [["1", "2", "3"], ["10", "11", "12"]],
    result = array1.reduce((r, a, i) =>
        r.concat(getCartesian({ array1: a, array2: array2[i] })), [])

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

您可以仅在第二个数组上使用map()方法,然后在嵌套数组上使用另一个map()方法。最后,使用索引将第一个数组中的“ nth”个元素与“ nth”个嵌套数组中的元素归为一个对象,如下所示:

array1 = ["a","b"]
array2 = [ ["1","2","3"],["10","11","12"]]
let x = [];

array2.map((e,i) => { // call function on every element in array2 with index callback
  e.map((f,j) => { // call function on every element in the nested arrays with index callback
    let obj = {};
    obj["array1"] = array1[i];
    obj["array2"] = f;
    x.push(obj);
  });
});

console.log(x);

答案 3 :(得分:0)

这与 Marks Meyer 答案类似,但是使用的是forEach()而不是reduce()

let array1 = ["a","b", "c"];
let array2 = [["1","2","3"], ["10","11","12"]];
let res = [];

array1.forEach((x, i) =>
{
    if (array2[i])
        res.push(...array2[i].map(y => ({array1: x, array2: y})));
});

console.log(res);

答案 4 :(得分:0)

您可以使用.map().flat()array2的每个元素映射array1的每个元素,然后展平结果数组。

const array1 = ["a","b"]
const array2 = [ ["1","2","3"],["10","11","12"]]

let res = array1.map((array1, i) => array2[i].map(array2 => ({array1, array2}))).flat()

console.log(res)