Search code examples
javascriptarraysdictionaryobject

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!


Solution

  • 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.