Friday, March 6, 2020

Javascript examples - Convert Array of objects to Map type| typescript

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

Map is a new type introduced in ES6 which holds key and value pairs using hash map data structure.
Given a array of objects

var arrayObjects = [
    { sid: '11', name: 'john' },
    { sid: '14', name: 'tom' }
];
In this blog post, I will take you to an examples for convert array to map with key and values in javascript.

Javascript array to MAP example 

Array.map function() calls the callback for each element of array iteration and create key and value element, finally returns new array of key and values into Map constructor. Printing map object to console using 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 super set of javascript with additional features type assertions.
  • During iteration of array, each key is typed as [string,string].
  • finally add the array into 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' }

Related article


EmoticonEmoticon