0

I have an array of objects, and I would like to group them into new objects based on the title. How would I do this?

This is my array of objects. What is the best way to match up based on title?

{
items: [
{
_id: "5f26b025e881790d5df93cae",
title: "Slim Fit Mesh Polo Shirt",
standardPrice: 99,
salePrice: 69.3,
image: "https://www.rlmedia.io/is/image/PoloGSI/s7-1351620_lifestyle?$rl_df_pdp_5_7_lif$",
created: "2020-08-01T12:23:01.054Z",
__v: 0
},
{
_id: "5f26b025e881790d5df93caf",
title: "Cotton Quarter-Zip Sweater",
standardPrice: 160,
salePrice: 160,
image: "https://www.rlmedia.io/is/image/PoloGSI/s7-1303140_lifestyle?$rl_df_pdp_5_7_lif$",
created: "2020-08-01T12:23:01.402Z",
__v: 0
},
{
_id: "5f26b8d1b2a6750d93b98ed1",
title: "Slim Fit Mesh Polo Shirt",
standardPrice: 99,
salePrice: 69.3,
image: "https://www.rlmedia.io/is/image/PoloGSI/s7-1351620_lifestyle?$rl_df_pdp_5_7_lif$",
created: "2020-08-02T13:00:01.208Z",
__v: 0
},
{
_id: "5f26b8d1b2a6750d93b98ed2",
title: "Cotton Quarter-Zip Sweater",
standardPrice: 160,
salePrice: 160,
image: "https://www.rlmedia.io/is/image/PoloGSI/s7-1303140_lifestyle?$rl_df_pdp_5_7_lif$",
created: "2020-08-02T13:00:01.671Z",
__v: 0
}
]
}

1 Answers1

1

A simple approach is to use a Map to group the objects based on the title:

let obj = {
items: [
{
_id: "5f26b025e881790d5df93cae",
title: "Slim Fit Mesh Polo Shirt",
standardPrice: 99,
salePrice: 69.3,
image: "https://www.rlmedia.io/is/image/PoloGSI/s7-1351620_lifestyle?$rl_df_pdp_5_7_lif$",
created: "2020-08-01T12:23:01.054Z",
__v: 0
},
{
_id: "5f26b025e881790d5df93caf",
title: "Cotton Quarter-Zip Sweater",
standardPrice: 160,
salePrice: 160,
image: "https://www.rlmedia.io/is/image/PoloGSI/s7-1303140_lifestyle?$rl_df_pdp_5_7_lif$",
created: "2020-08-01T12:23:01.402Z",
__v: 0
},
{
_id: "5f26b8d1b2a6750d93b98ed1",
title: "Slim Fit Mesh Polo Shirt",
standardPrice: 99,
salePrice: 69.3,
image: "https://www.rlmedia.io/is/image/PoloGSI/s7-1351620_lifestyle?$rl_df_pdp_5_7_lif$",
created: "2020-08-02T13:00:01.208Z",
__v: 0
},
{
_id: "5f26b8d1b2a6750d93b98ed2",
title: "Cotton Quarter-Zip Sweater",
standardPrice: 160,
salePrice: 160,
image: "https://www.rlmedia.io/is/image/PoloGSI/s7-1303140_lifestyle?$rl_df_pdp_5_7_lif$",
created: "2020-08-02T13:00:01.671Z",
__v: 0
}
]
};
let map = {};
let list = obj.items;
for(let i = 0; i < list.length; i++){
     let item = list[i];
     if(!map[item.title])
          map[item.title] = [item];
     else
          map[item.title].push(item);
}
console.log(Object.values(map));
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48