SimonBoh
SimonBoh

Reputation: 117

How can I map an Array or an Object to an Object?

Normally a map method returns an Array but I have had a lot use-cases where I would like to create an Object instead. Is there a JavaScript native way of doing this or a very simple and performant implementation? jQuery solutions are also welcome.

This is how the native Array map method works (EcmaScript 6):

console.log( [ 1, 2, 4 ].map( item => item * 10) );
// => [ 10, 20, 40 ]

This is how I imagine the method to work (in case it is JavaScript native):

console.log( [ 1, 2, 4 ].mapToObject(resolveMultiplyWithTen) );
// => { 1: 10, 2: 20, 4: 40 }

In this example, the method mapToObject should behave the same like map but return an Object instead of an Array. Callback resolveMultiplyWithTen would multiply the item with ten.

A problem which I see here is that the callback function can not return two values (key and value, e.g.: 1 and 20), which would be needed to efficiently create an Object.

This is how I always used to create an Object from Array:

/* Loop over Array and create key:value pairs in Object */
const arr = [ 1, 2, 4];
const obj = {};
for ( let i = 0; i < arr.length; i++ )
  obj[arr[i]] = arr[i] * 10;
console.log(obj);
// => { 1: 10, 2: 20, 4: 40 }

This is the most suiting solution I could think of:

/* Create an Object of each item via map and apply to Object.assign */
console.log(Object.assign.apply(null, [ 1, 2, 4 ].map( item => {
  const out = {};
  out[item] = item * 10;
  return out;
})));
// => { 1: 10, 2: 20, 4: 40 }

Is there any native JavaScript solution to this problem or a more performant way?

Upvotes: 0

Views: 69

Answers (2)

Maheer Ali
Maheer Ali

Reputation: 36564

Use reduce()

let res = [ 1, 2, 4 ].reduce((ac,a) => (ac[a] = a * 10,ac),{})
console.log(res)

Or you can also use Object.fromEntries

let res = Object.fromEntries([ 1, 2, 4 ].map(x => [x, x * 10]))
console.log(res)

Upvotes: 3

Code Maniac
Code Maniac

Reputation: 37755

You can just use reduce

let obj = [ 1, 2, 4 ].reduce( (op,inp) => (op[inp] = inp * 10, op),{} )

console.log(obj)

or you can use forEach

let data = [ 1, 2, 4 ]
let obj = {}

data.forEach(val=>{
  obj[val] = val * 10
})

console.log(obj)

Upvotes: 2

Related Questions