2020年12月31日星期四

Group objects in array by property value

I'm sure something similar has already been asked here, so I apologize in advance if this is redundant, but i did look and didn't find something that fit my specific needs. Hoping someone can help.

I have an array of pageSections:

const sections = [    {      data: {         order: 0,         title: "home_hero",         block_type: "hero",         pages: ["home"]             },    },    {      data: {        order: 0,        title: "about_hero",        block_type: "hero",        pages: ["about"],      },    },    {      data: {        order: 1,        title: "home_intro",        block_type: "content_block",        pages: ["home"],      },    },    {      data: {        order: 0,        title: "service_card1",        block_type: "card",        pages: ["home", "services"],      },    },    {      data: {        order: 1,        title: "service_card2",        block_type: "card",        pages: ["home", "services"],      },    },    {      data: {        order: 2,        title: "service_card3",        block_type: "card",        pages: ["home", "services"],      },    },  ];  

I'd like to group the each of the sections that are card blocks together into their own array on the same original array. So that the end result would be something like this:

const sections = [    {      data: {        order: 0,        title: "home_hero",        block_type: "hero",        pages: ["home"],      },    },    {      data: {        order: 0,        title: "about_hero",        block_type: "hero",        pages: ["about"],      },    },    {      data: {        order: 1,        title: "home_intro",        block_type: "content_block",        pages: ["home"],      },    },    [      {        data: {          order: 0,          title: "service_card1",          block_type: "card",          pages: ["home", "services"],        },      },      {        data: {          order: 1,          title: "service_card2",          block_type: "card",          pages: ["home", "services"],        },      },      {        data: {          order: 2,          title: "service_card3",          block_type: "card",          pages: ["home", "services"],        },      },    ],  ];  

I'm pretty sure that i'd need to use some combination of reduce, map and filter, but cannot seem to wrap my head around it. Any help would be greatly appreciated! Thank you!

https://stackoverflow.com/questions/65526843/group-objects-in-array-by-property-value January 01, 2021 at 10:06AM

没有评论:

发表评论