I have two arrays like so
var arr1 = ["1", "2", "3", "4"];
var arr2 = [["a", "b", "c", "d"], ["e", "f", "g", "h"], ["i", "j", "k", "l"], ["m", "n", "o", "p"], ["q", "r", "s", "t"]];
var newArr = [{1: "a", 2: "b", 3: "c", 4: "d"}, {1: "e", 2: "f", 3: "g", 4: "h"}, {1: "i", 2: "j", 3: "k", 4: "l"}, {1: "m", 2: "n", 3: "o", 4: "p"}, {1: "q", 2: "r", 3: "s", 4: "t"}];
Assuming the input always matches, I'd start with arr2
:
arr2.map(x =>
However, at this point what you want is to zip
values from x
and the corresponding values from y
together, so let's introduce a helper first (I'm actually gonna call it zipKeyVal
1 because it maps values from first param to keys, and the second to values).
function zipKeyVal(a,b) {
var result = {};
for (var i = 0; i < a.length; i++) {
result[a[i]] = b[i];
}
return result;
}
With that, our solution becomes:
var newArr = arr2.map(x => zipKeyVal(arr1, x));
1Oh, apparently underscore.js calls that _.object
, and lodash zipObject
.