How To Convert Array To Map Using Node Js?


Share:
Published By: Admin, Published On: Jan 11, 2022, Category: Node JS


Hello Friends,

This article will give you example of node js convert array to map example. I explained simply about node js convert array to map. This tutorial will give you simple example of convert map from array. This is a short guide on use node js convert array to map function in nodejs

In this post, you'll learn how to use convert array to map function in node js. i will show you nodejs convert array to map() method. we will use convert array to map function given below.

Here i will give you many example of how to use convert array to map function in node js.

Example 1 :

Step 1 : Create Node App

Run following command to create node app.

mkdir my-app
cd my-app
 
npm init
Step 2 : Create server.js file

server.js

var temp2 = [
    { temp: 'subject', val: 'laravel' },
    { temp: 'product', val: 'laptop' }
];

var ans = temp2.reduce(function(map, obj) {
    map[obj.temp] = obj.val;
    return map;
}, {});

console.log(ans);

now you can simply run by following command:

node server.js
Output :
{ subject: 'laravel', product: 'laptop' }

Example 2 :

Step 1 : Create Node App

Run following command to create node app.

mkdir my-app
cd my-app
 
npm init
Step 2 : Create server.js file

server.js

let temp = [
  	{ key: 'subject', val: 'laravel' },
  	{ key: 'subject2', val: 'dell' },
  	{ key: 'subject3', val: 'javascript' }
];

let temp2 = temp.reduce((t1, obj) => {
  	t1.set(obj.key, obj.val);

  	return t1;
}, new Map());

console.log(temp2);
console.log(temp2.size);

now you can simply run by following command:

node server.js
Output :
Map {
  'subject' => 'laravel',
  'subject2' => 'dell',
  'subject3' => 'javascript' }
3

It will help you...

Share: