{

Javascript Convert Array of objects to Map type example


An array of objects are a list of object enclosed in [], each object holds key and value pairs.

The map is a new type introduced in ES6 that holds key and value pairs using the hash map data structure.
Given an array of objects

  
var arrayObjects = [  
    { sid: '11', name: 'john' },  
    { sid: '14', name: 'tom' }  
];  

In this blog post, I will take you to examples for converting an array to a map with keys and values in javascript.

Javascript array to MAP example

Array.map function() calls the callback for each element of array iteration and creates key and value elements, finally returning a new array of keys and values into the Map constructor. Printing map object to console using the console.dir() function.

var result = new Map(arrayObjects.map(key => [key.sid, key.name]));  
console.dir(result);  

And output is

Map { '11' => 'john', '14' => 'tom' }

Typescript example,transfer array of objects to HashMap type

The below explains about following things.

  • Typescript is a superset of javascript with additional features type assertions.
  • During iteration of an array, each key is typed as [string, string].
  • finally, add the array into the map
var arrayObjects = [  
    { sid: '11', name: 'john' },  
    { sid: '14', name: 'tom' }  
  
];  
var result = new Map(arrayObjects.map(key => [key.sid, key.name] as [string, string]));  
console.log(result)  

Output is

Map { '11' => 'john', '14' => 'tom' }  

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.