Combine the values of two arrays into object

前端 未结 5 1585
遥遥无期
遥遥无期 2021-01-21 08:43

I have two arrays:

array1 = [\"Bob\", \"John\", \"Dave\"];
array2 = [1, 2, 3];

Is there combine the two into a javascript array filled with obj

5条回答
  •  孤独总比滥情好
    2021-01-21 09:16

    You could use an object and iterate the keys and the values.

    var array1 = ["Bob", "John", "Dave"],
        array2 = [1, 2, 3],
        object = { meta: array1, value: array2 },
        result = Object.keys(object).reduce(function (r, k) {
            object[k].forEach(function (a, i) {
                r[i] = r[i] || {};
                r[i][k] = a;
            });
            return r;
        }, []);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题