Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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': 'B',
'3': 'C',
'4': 'D',
'5': 'E',
}

Thanks in advance

like image 243
3nath Avatar asked Jul 30 '14 13:07

3nath


3 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);
like image 180
bencripps Avatar answered Oct 27 '22 00:10

bencripps


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

like image 20
Rajaprabhu Aravindasamy Avatar answered Oct 27 '22 00:10

Rajaprabhu Aravindasamy


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);
like image 1
Abhijeet Avatar answered Oct 26 '22 22:10

Abhijeet