6

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',
}
2
  • 3
    Do you have something against loops? Commented Jul 30, 2014 at 13:03
  • 7
    Sounds like homework. Commented Jul 30, 2014 at 13:04

4 Answers 4

7

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);

Sign up to request clarification or add additional context in comments.

1 Comment

.forEach is a loop.
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

2 Comments

$.each() is not a loop anymore :)?
map is essentially a loop too, but whatever :p
1

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);

Comments

0

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 = 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"}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.