I have an array of objects like this:
const data = [
{ id: 1, type: { name: "A" }, condition: "new" },
{ id: 2, type: { name: "C" }, condition: "broken" },
{ id: 3, type: { name: "C" }, condition: "brand new" },
{ id: 4, type: { name: "B" }, condition: "broken" },
{ id: 5, type: { name: "C" }, condition: "brand new" },
{ id: 6, type: { name: "A" }, condition: "new" },
{ id: 7, type: { name: "A" }, condition: "new" },
{ id: 8, type: { name: "B" }, condition: "broken" },
{ id: 9, type: { name: "C" }, condition: "broken" }
];
What i'm trying to do is to group those objects by type's key:value in this case by name:value, like this:
const data = [
{
by: {
type: { name: "A" }
},
chunks: [
{ id: 1, type: { name: "A" }, condition: "new" },
{ id: 6, type: { name: "A" }, condition: "new" },
{ id: 7, type: { name: "A" }, condition: "new" }
]
},
{
by: {
type: { name: "C" }
},
chunks: [
{ id: 2, type: { name: "C" }, condition: "broken" },
{ id: 3, type: { name: "C" }, condition: "brand new" },
{ id: 5, type: { name: "C" }, condition: "brand new" },
{ id: 9, type: { name: "C" }, condition: "broken" }
]
},
{
by: {
type: { name: "B" }
},
chunks: [
{ id: 4, type: { name: "B" }, condition: "broken" },
{ id: 8, type: { name: "B" }, condition: "broken" }
]
},
];
I've tried to use lodash and Array.prototype.reduce() , my last attempt was using lodash, but i can't get the type as object.
_.chain(channels)
.groupBy("type.name")
.map((item, i) => {
return {
chunks: item,
by: i
};
})
.value();