Create a dictonary-like object from a list of objects using an specfic value from each object.
npm i map-items-by-keys
The name of the fields to use as Keys. Can be a Single Key or Multiple ones.
- Type: string or Array of string
- Example:
'id'
['id', 'name']
⚠️ If some item hasn't the field will be ignored
The list of items to be mapped.
- Type: Array of objects
- Example:
[
{ "id": 1, "name": "Bruce Wayne", "hero": "Batman" },
{ "id": 2, "name": "Tony Stark", "hero": "Ironman" }
]
This refers if the values of the keys are unique. This indicate if the final map will save as an array (false
) or an object (false
).
- Type: Boolean
- Default:
true
const mapItemsBy = require('map-items-by-keys');
const items = [
{ id: 1, name: "Bruce Wayne", hero: "Batman" },
{ id: 2, name: "Tony Stark", hero: "Ironman" }
]
const itemsMapped = mapItemsBy("id", items);
/*
output:
{
1: { id: 1, name: "Bruce Wayne", hero: "Batman" },
2: { id: 2, name: "Tony Stark", hero: "Ironman" }
}
*/
const mapItemsBy = require('map-items-by-keys');
const items = [
{ id: 1, name: "Bruce Wayne", hero: "Batman" },
{ id: 2, name: "Tony Stark", hero: "Ironman" },
{ id: 3, name: "Richard Grayson", hero: "Batman" }
]
const itemsMapped = mapItemsBy("hero", items, false);
/*
output:
{
Batman: [
{ id: 1, name: Bruce Wayne, hero: "Batman" },
{ id: 3, name: "Richard Grayson", hero: "Batman" }
],
Ironman: [
{ id: 2, name: Tony Stark, hero: "Ironman" }
]
}
*/
const mapItemsBy = require('map-items-by-keys');
const items = [
{ id: 1, name: "Bruce Wayne", hero: "Batman", brand: "DC" },
{ id: 2, name: "Tony Stark", hero: "Ironman", brand: "Marvel" }
]
const itemsMapped = mapItemsBy(["brand", "id"], items);
/*
output:
{
DC: {
1: { id: 1, name: "Bruce Wayne", hero: "Batman" }
},
Marvel: {
2: { id: 2, name: "Tony Stark", hero: "Ironman" }
}
}
*/
const mapItemsBy = require('map-items-by-keys');
const items = [
{ id: 1, name: "Bruce Wayne", hero: "Batman", brand: "DC" },
{ id: 2, name: "Tony Stark", hero: "Ironman", brand: "Marvel" },
{ id: 3, name: "Richard Grayson", hero: "Batman", brand: "DC" }
]
const itemsMapped = mapItemsBy(["brand", "hero"], items, false);
/*
output:
{
DC: {
Batman: [
{ id: 1, name: "Bruce Wayne", hero: "Batman" },
{ id: 3, name: "Richard Grayson", hero: "Batman", brand: "DC" }
]
},
Marvel: {
Ironman: [
{ id: 2, name: "Tony Stark", hero: "Ironman" }
]
}
}
*/