Javascript map array of objects

Convert JavaScript Map to Array of Objects

  • 29 Sep, 2021
  • 3 min read

Let's suppose you have the following JavaScriptMap object:

const myMap = new Map();
myMap.set('foo', 1);
myMap.set('bar', 2);
myMap.set('baz', 3);

To convert it into an array of objects, for example, like so:

/* [
    {key: 'foo', value: 1},
    {key: 'bar': value: 2},
    {key: 'baz': value: 3},
] */

You can do any of the following:

  • Use Array.from();
  • Use the spread operator with Array.prototype.map();
  • Iterate over Map and add elements to array.

Using Array.from()

Since Array.from() works on iterables such as Map, you can simply pass it as an argument to Array.from(). This would result in an array of arrays containing key and value from the Map. To illustrate this, consider for example, the following:

const arr = Array.from(myMap);

console.log(arr); // [['foo', 1], ['bar', 2], ['baz', 3]]

To transform this array of arrays into an array of objects, you can simply pass a map function as the second (optional) argument to Array.from() which will be called on every element of the array. For example:

const arr = Array.from(myMap, function (item) {
    return { key: item[0], value: item[1] }
});

console.log(arr);

/* [
    {key: 'foo', value: 1},
    {key: 'bar': value: 2},
    {key: 'baz': value: 3},
] */

You can shorten the map function to a one-liner by using; an arrow function, and destructing syntax in the callback function argument, like so:

const arr = Array.from(myMap, ([key, value]) => ({ key, value }));

console.log(arr);

/* [
    {key: 'foo', value: 1},
    {key: 'bar': value: 2},
    {key: 'baz': value: 3},
] */

Using the Spread Operator With Array.prototype.map()

You can use the spread operator on Map to unpack its elements into an array, for example, like so:

const arr = [...myMap];

console.log(arr); // [['foo', 1], ['bar', 2], ['baz', 3]]

As you can see, this results in an array of arrays containing key and value from the Map object. To transform this into an array of objects instead, you can call the Array.prototype.map() method on the resulting array, for example, in the following way:

const arr = [...myMap].map(function (item) {
    return { key: item[0], value: item[1] }
});

console.log(arr);

/* [
    {key: 'foo', value: 1},
    {key: 'bar': value: 2},
    {key: 'baz': value: 3},
] */

You can shorten the map function to a one-liner by using; an arrow function, and destructing syntax in the callback function argument, like so:

const arr = [...myMap].map(([key, value]) => ({ key, value }));

console.log(arr);

/* [
    {key: 'foo', value: 1},
    {key: 'bar': value: 2},
    {key: 'baz': value: 3},
] */

Iterating Over Map and Adding Elements to Array

You can simply iterate over the Map object using any compatible iteration method and add each item as an object to the resulting array.

For example, you can use Map.prototype.forEach() in the following way:

const arr = [];

myMap.forEach((value, key) => arr.push({ key, value }));

console.log(arr);

/* [
    {key: 'foo', value: 1},
    {key: 'bar': value: 2},
    {key: 'baz': value: 3},
] */

Or, alternatively, you may use the for...of loop like so:

const arr = [];

for (const [key, value] of myMap) {
    arr.push({ key, value });
}

console.log(arr);

/* [
    {key: 'foo', value: 1},
    {key: 'bar': value: 2},
    {key: 'baz': value: 3},
] */


Hope you found this post useful. It was published 29 Sep, 2021. Please show your love and support by sharing this post.

  • Web Development
  • Frontend
  • JavaScript
  • Backend
  • Node.js

Examples

Return a new array with the square root of all element values:

const numbers = [4, 9, 16, 25];
const newArr = numbers.map(Math.sqrt)

Try it Yourself »

Multiply all the values in an array with 10:

const numbers = [65, 44, 12, 4];
const newArr = numbers.map(myFunction)

function myFunction(num) {
  return num * 10;
}

Try it Yourself »

More examples below.


Definition and Usage

map() creates a new array from calling a function for every array element.

map() calls a function once for each element in an array.

map() does not execute the function for empty elements.

map() does not change the original array.


Syntax

array.map(function(currentValue, index, arr), thisValue)

Parameters

Parameter Description
function() Required.
A function to be run for each array element.
currentValue Required.
The value of the current element.
index Optional.
The index of the current element.
arr Optional.
The array of the current element.
thisValue Optional.
Default value undefined.
A value passed to the function to be used as its this value.

Return Value

Type Description
An array The results of a function for each array element.


More Examples

Get the full name for each person:

const persons = [
  {firstname : "Malcom", lastname: "Reynolds"},
  {firstname : "Kaylee", lastname: "Frye"},
  {firstname : "Jayne", lastname: "Cobb"}
];

persons.map(getFullName);

function getFullName(item) {
  return [item.firstname,item.lastname].join(" ");
}

Try it Yourself »


Browser Support

map() is an ECMAScript5 (ES5) feature.

ES5 (JavaScript 2009) fully supported in all browsers:

Chrome IE Edge Firefox Safari Opera
Yes 9-11 Yes Yes Yes Yes

How do you map an array of objects?

How to use Javascript ..
Simple iteration over array of objects..
Create new trasformed array..
Get list of values of a object property..
Add properties to every object entry of array..
Delete a property of every object entry in array..
Access key/value pairs of each object enty..

How do I map an array in JavaScript?

The syntax for the map() method is as follows: arr. map(function(element, index, array){ }, this); The callback function() is called on each array element, and the map() method always passes the current element , the index of the current element, and the whole array object to it.

Can you map objects in JavaScript?

Map is a collection of elements where each element is stored as a Key, value pair. Map object can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key, value pair in the same order as inserted.

How do you access an array of objects?

A nested data structure is an array or object which refers to other arrays or objects, i.e. its values are arrays or objects. Such structures can be accessed by consecutively applying dot or bracket notation. Here is an example: const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };