Skip to content

vishalash/object-array-to-map

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 

Repository files navigation

Object Array to Map Converter

This is a small JavaScript utility function that takes an array of objects and converts it into a Map of objects grouped by a specified key.

Usage

To use this function, simply import it into your JavaScript file and call it with two parameters:

const objectArrayToMap  = require('object-array-to-map');

const arr = [{id: 1, name: 'John'}, {id: 2, name: 'Jane'}, {id: 3, name: 'John'}]; const key = 'name';

const map = objectArrayToMap(arr, key); console.log(map);

This will output a Map object containing the grouped objects:

Map(2) {
  'John' => [ { id: 1, name: 'John' }, { id: 3, name: 'John' } ],
  'Jane' => [ { id: 2, name: 'Jane' } ]
}

Parameters

The objectArrayToMap function takes two parameters:

  • arr (Array): The array of objects to convert.
  • key (string): The name of the key to group the objects by.

Return Value

The objectArrayToMap function returns a Map object containing the grouped objects.

Implementation Details

The `objectArrayToMap` function uses the Array.prototype.reduce method to iterate over the input array and group the objects by the specified key. It creates a new Map object and populates it with the grouped objects. If an object with the same key already exists in the Map, the current object is appended to its corresponding array; otherwise, a new key-value pair is created in the Map.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published