问题描述
我需要处理我的一些数据。有一个对象数组。这些对象之一是“活动的”。我拼接了活动房间并将其放置在数组的索引 0 处。现在我需要删除更多数据并且遇到问题。只有一个 roomActive: true
和只有一个 sectionActive: true
const exhibitions = [
{
title: "Lobby",roomActive: false,sections: [
{ id: 4,sectionActive: false },{ id: 5,{ id: 6,{ id: 7,sectionActive: false }
]
},{
title: "First Room",sections: [
{ id: 8,{ id: 9,{ id: 10,{ id: 11,{
title: "Second Room",roomActive: true,sections: [
{ id: 12,{ id: 13,sectionActive: true },{ id: 14,{ id: 15,{
title: "Fourth Room",sections: [
{ id: 16,{ id: 17,{ id: 18,{ id: 19,sectionActive: false }
]
}
要将 sectionActive 放在索引 0 处,我会这样做:
const handleTimelineClose = () => {
const newArray = [...exhibitions]
newArray.find((item,i) => {
return item.roomActive === true
&& newArray.unshift(newArray.splice(i,1)[0])
})
return newArray
}
这个函数把这个对象放在索引 0 处:
{
title: "Second Room",sectionActive: false }
]
}
但我还需要操作这个 sections
对象的 roomActive: true
数组。我需要找到并保留 sectionActive: true
的对象和下一个索引中的对象。但我不知道如何做到这一点。
{
title: "Second Room",sections: [
{ id: 13,]
}
预期结果:
const exhibitions = [
{
title: "Second Room",]
},{
title: "Lobby",sections: [
{ id: 4,sectionActive: false }
]
},{
title: "First Room",sections: [
{ id: 8,{
title: "Fourth Room",sections: [
{ id: 16,sectionActive: false }
]
}
解决方法
您可以通过查看属性来过滤数组并检查前一个属性是否为 true
。
const
sections = [{ id: 12,sectionActive: false },{ id: 13,sectionActive: true },{ id: 14,{ id: 15,sectionActive: false }],trueAndNext = sections
.filter(({ sectionActive },i,a) => sectionActive || a[i -1]?.sectionActive);
console.log(trueAndNext);
.as-console-wrapper { max-height: 100% !important; top: 0; }