lumpinto
v1.0.15
Published
Package for grouping array objetcts by key
Downloads
30
Maintainers
Readme
LUMPINTO PACKAGE
This package will rearrange an array of objects, grouping them by a selected key. This package is especially useful if you are fetching rows from a relational database and you need to group the rows by a specific column.
Example
Say you have an array of objects like the following:
const myArray = [
{
brand: "Audi",
model: "A1"
},
{
brand: "Audi",
model: "A2"
},
{
brand: "Audi",
model: "TT"
},
]
Clearly, the objects are of type 'car', as in:
myArray[0] = {
brand: "Audi",
model: "A1"
},
With Lumpinto Package, you can lump all these objects into a new object. Let's say you want to group these objects by the key brand. The function lumpinto() requires 3 params:
1st param: Array Which is the original array of objects.
2nd param: keyToGroupBy The key of the object that you wish to have the array grouped by.
3rd param: keyForTheContent The name of the key that you wish the new object to have.
So, if we want our Array myArray to have all cars in one object called cars, we must do:
const newGroup = lumpinto(myArray, 'brand', 'cars')
if you console.log(newGroup), you will see:
newGrouped = [
{
"brand":"Audi",
"cars":[
{"model":"A1"},
{"model":"A2"},
{"model":"TT"}
]
}
]
Complex arrays
If you array is more complex than the one in the example above, this package will still work just fine. Say now your array of objects is like the following:
const myComplexArray = [
{
brand: "Audi",
color: "red",
model: "A1"
},
{
brand: "Audi",
color: "yellow",
model: "A2"
},
{
brand: "Audi",
color: "black",
model: "A3"
},
{
brand: "Audi",
color: "dark blue",
model: "TT"
},
{
brand: "BMW",
color: "dark blue",
model: "X5"
},
{
brand: "BMW",
color: "amber",
model: "i4"
},
{
brand: "FORD",
color: "amber",
model: "Focus"
},
{
brand: "FORD",
color: "white",
model: "Fiesta"
},
{
brand: "FORD",
color: "black",
model: "Mustang"
}
]
const newComplexGrouped = lumpinto(myArray, 'brand', 'cars')
if you console.log(newComplexGrouped), you will see:
newComplexGrouped = [
{
"brand":"Audi",
"cars":[
{"color":"red","model":"A1"},
{"color":"yellow","model":"A2"},
{"color":"black","model":"A3"},
{"color":"dark blue","model":"TT"}
]
},
{
"brand":"BMW",
"cars":[
{"color":"dark blue","model":"X5"},
{"color":"amber","model":"i4"}
]
},
{
"brand":"FORD",
"cars":[
{"color":"amber","model":"Focus"},
{"color":"white","model":"Fiesta"},
{"color":"black","model":"Mustang"}
]
}
] x
Thanks
Developer Rennan Leal de Meirelles 😎
No need to buy me a ☕ coffe ☕ as I already drink too much, more than i should. And i know, most of you do the same.