object-array-to-map

1.0.3 • Public • Published

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.

Readme

Keywords

Package Sidebar

Install

npm i object-array-to-map

Weekly Downloads

4

Version

1.0.3

License

ISC

Unpacked Size

3.92 kB

Total Files

4

Last publish

Collaborators

  • vishalash