gpt4 book ai didi

javascript - 如何映射和过滤数组对象?

转载 作者:行者123 更新时间:2023-12-04 15:11:01 25 4
gpt4 key购买 nike

我在下面存储了数据。我想根据标题过滤卡片。我正在 react-trello board 上实现实时搜索以使用react,但找不到解决方案:

数据:

  const data = {
lanes: [
{
id: 'lane1',
title: 'Planned Tasks',
label: '2/2',
cards: [
{id: 'Card1', title: 'Write Blog', description: 'Can AI make memes', label: '30 mins', draggable: false},
{id: 'Card2', title: 'Pay Rent', description: 'Transfer via NEFT', label: '5 mins', metadata: {sha: 'be312a1'}}
]
},
{
id: 'lane2',
title: 'Completed',
label: '0/0',
cards: []
}
]
}

这是我试过的。

 const newData = data.lanes
.map((lane) => {
lane.cards.filter((card) => {
return card.title.toLowerCase().includes(search.toLowerCase());
});
})
.flat();

如有任何帮助,我们将不胜感激。

最佳答案

你只是忘了在 map 的调用中 return (即 filter 的结果):

const data = {
lanes: [
{
id: 'lane1',
title: 'Planned Tasks',
label: '2/2',
cards: [
{id: 'Card1', title: 'Write Blog', description: 'Can AI make memes', label: '30 mins', draggable: false},
{id: 'Card2', title: 'Pay Rent', description: 'Transfer via NEFT', label: '5 mins', metadata: {sha: 'be312a1'}}
]
},
{
id: 'lane2',
title: 'Completed',
label: '0/0',
cards: []
}
]
}

const search = "Write"

const newData = data.lanes
.map((lane) => {
return lane.cards.filter((card) => {
return card.title.toLowerCase().includes(search.toLowerCase());
});
})
.flat();

console.log(newData);

如果你想要数据的原始形状只有带有匹配卡片的 channel

const data = {
lanes: [
{
id: 'lane1',
title: 'Planned Tasks',
label: '2/2',
cards: [
{id: 'Card1', title: 'Write Blog', description: 'Can AI make memes', label: '30 mins', draggable: false},
{id: 'Card2', title: 'Pay Rent', description: 'Transfer via NEFT', label: '5 mins', metadata: {sha: 'be312a1'}}
]
},
{
id: 'lane2',
title: 'Completed',
label: '0/0',
cards: []
}
]
}

const search = "Write"

const cardMatch = card => card.title.toLowerCase().includes(search.toLowerCase())

const newData = data.lanes
.map(lane => ({...lane, cards: lane.cards.filter(cardMatch)}))
.filter(lane => lane.cards.length > 0)

console.log(newData);

关于javascript - 如何映射和过滤数组对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65198510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com