Javascript: Convert map to array of objects

Viewed 1200

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!

4 Answers

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.

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

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

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})
}
Related