Create Object From Two Arrays
How can I create an object from two arrays without using loops in javascript. example: array1 = [1,2,3,4,5]; array2 = [A,B,C,D,E]; I want from below object obj = { '1': 'A', '2':
Solution 1:
var obj = {}
array1 = [1, 2, 3, 4, 5];
array2 = ['A', 'B', 'C', 'D', 'E'];
array1.forEach(function(value, index) {
obj[value] = array2[index];
});
console.log(obj);
Solution 2:
Try to use $.each()
to iterate over one of that array and construct the object as per your requirement,
var array1 = [1,2,3,4,5],array2 = ['A','B','C','D','E'];
var obj = {};
$.each(array2,function(i,val){
obj[array1[i]] = val;
});
DEMO
Solution 3:
An ES6, array reduce solution.
const array1 = [1, 2, 3, 4, 5];
const array2 = ['A', 'B', 'C', 'D', 'E'];
const resultMap = array1.reduce(
(accumulator, value, index) =>Object.assign(accumulator, {
[value]: array2[index],
}), {}
);
console.log(resultMap);
Solution 4:
just for fun created something like this without using any iteration methods.
const array1 = [1,2,3,4,5];
const array2 = ['A','B','C','D','E'];
let combineKeyValueProxy = newProxy({}, {
set: function(target, prop, value, receiver) {
target[array1[prop]] = value;
returntrue
}
});
const output = Object.assign(combineKeyValueProxy, array2);
console.log(output) // Proxy {1: "A", 2: "B", 3: "C", 4: "D", 5: "E"}
Post a Comment for "Create Object From Two Arrays"