J.Ko
J.Ko

Reputation: 8791

Javascript: Convert map to array of objects

I am new to programming in general and am looking to convert a Javascript map into array of objects. For example, convert the input constant into the output constant:

const input = new Map([
   [1, 'one'],
   [2, 'two'],
   [3, 'three'],
]);

const output = [
    { number: 1, letter: 'one' },
    { number: 2, letter: 'two' },
    { number: 3, letter: 'three' }
];

This might be a simple code but I cannot find any reference. Any advice? Thanks!

Upvotes: 2

Views: 5414

Answers (5)

Géry Ogam
Géry Ogam

Reputation: 8107

Contrary to other answers, this one does not create an unnecessary intermediate array:

const input = new Map([
  [1, 'one'],
  [2, 'two'],
  [3, 'three'],
]);
const output = Array.from(input, ([number, letter]) => ({number, letter}));
console.log(output);

From MDN:

Array.from() has an optional parameter mapFn, which allows you to execute a function on each element of the array being created, similar to map(). More clearly, Array.from(obj, mapFn, thisArg) has the same result as Array.from(obj).map(mapFn, thisArg), except that it does not create an intermediate array, and mapFn only receives two arguments (element, index) without the whole array, because the array is still under construction.

Upvotes: 0

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11011

Use ... operator and map method.

const input = new Map([
   [1, 'one'],
   [2, 'two'],
   [3, 'three'],
]);

const output = [...input].map(([number, letter]) => ({number, letter}))

console.log(output);

Upvotes: 1

Subhash Jha
Subhash Jha

Reputation: 38

You can do it by iterating over the Map using For-of iteration and pushing the object into a new array. Refer to for-of operation for Map

var arr = [];
for(var [key, val] of input) {
  arr.push({ integer: key, letter: val})
}

Upvotes: 0

Md Sabbir Alam
Md Sabbir Alam

Reputation: 5064

You don't have to convert to anything. There is a forEach method for Map. You can do the following using Map.protoType.forEach,

const input = new Map([
   [1, 'one'],
   [2, 'two'],
   [3, 'three'],
]);

let output = [];

input.forEach((letter, number) => {
  output.push({number, letter});
})

console.log(output);

Upvotes: 1

Andreas Louv
Andreas Louv

Reputation: 47127

Something like this might work:

const output = Array.from(input).map(([number, letter]) => ({number, letter}));

The basic idea is that you convert the map input to an array, and then map each entry.

Upvotes: 6

Related Questions