Create an object from two arrays

How to 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 a bottom object

 obj = { '1': 'A', '2': 'B', '3': 'C', '4': 'D', '5': 'E', } 

Thanks in advance

+4
javascript jquery
source share
4 answers

 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); 
+5
source share

Try using $.each() to iterate over one of this array and construct the object according to 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

+2
source share

ES6 solution, reduces the array.

 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); 
0
source share

just for fun created something like this without using any iterative methods.

 const array1 = [1,2,3,4,5]; const array2 = ['A','B','C','D','E']; let combineKeyValueProxy = new Proxy({}, { set: function(target, prop, value, receiver) { target[array1[prop]] = value; return true } }); const output = Object.assign(combineKeyValueProxy, array2); console.log(output) // Proxy {1: "A", 2: "B", 3: "C", 4: "D", 5: "E"} 
0
source share

All Articles