Reputation: 1844
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"]];
What I would like to do is merge the two arrays to form a final output that looks like this
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"}];
So effectively take each array out of the second array and then merge it with the first array to form an object.
I was just wandering what the most efficient way to do this in javascript would be?
Any help would be much appreciated
Thanks for your time
Upvotes: 0
Views: 96
Reputation: 39370
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(keys,values) {
var result = {};
for (var i = 0; i < keys.length; i++) {
result[keys[i]] = values[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
.
Upvotes: 1
Reputation: 8926
You could use two map
functions and some ES6 features:
var newArr = arr2.map(el => el.map((e, i) => ({ [arr1[i]]: e })));
Working example:
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 = arr2.map(el => el.map((e, i) => ({ [arr1[i]]: e })));
document.write('<pre>' + JSON.stringify(newArr, 0, 2) + '</pre>');
Upvotes: 1
Reputation: 1795
Using Underscore:
var newArr = _.map(arr2, function(arr) {
return _.object(arr1, arr);
});
Upvotes: 1
Reputation: 386560
You could use some array methods like Array#map
and
Array#forEach
.
var arr1 = ["1", "2", "3", "4"],
arr2 = [["a", "b", "c", "d"], ["e", "f", "g", "h"], ["i", "j", "k", "l"], ["m", "n", "o", "p"], ["q", "r", "s", "t"]],
newArr = arr2.map(function (a) {
var o = {};
arr1.forEach(function (b, i) {
o[b] = a[i];
});
return o;
});
document.write('<pre>' + JSON.stringify(newArr, 0, 4) + '</pre>');
Upvotes: 1