我敢肯定这里已经有人问过类似的问题,所以如果这是多余的,我提前道歉,但我确实看了看并没有找到适合我特定需求的东西。希望有人能帮忙。
我有一个 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"],
},
},
];
我想将作为卡片块的每个部分组合到同一个原始阵列上的它们自己的阵列中。所以最终的结果是这样的:
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"],
},
},
],
];
我很确定我需要使用 reduce、map 和 filter 的某种组合,但似乎无法解决它。任何帮助将不胜感激!谢谢!
我非常有信心有一种方法可以在一行中做到这一点,但我无法弄清楚。
但是,这是一个 2-lined 解决方案,可以实现您想要的:
let grouped = sections.filter(section => section.data.block_type !== "card");
grouped.push(sections.filter(section => section.data.block_type == "card"));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句