给出以下数据结构
const list = [
{
title: 'Section One',
data: [
{
title: 'Ay',
},
{
title: 'Bx',
},
{
title: 'By',
},
{
title: 'Cx',
},
],
},
{
title: 'Section Two',
data: [
{
title: 'Ay',
},
{
title: 'Bx',
},
{
title: 'By',
},
{
title: 'Cx',
},
],
},
];
我想要做的事情是基于每个对象的数据数组中的title属性来过滤此列表。 一个示例是具有列表,其中子项的title属性以“ B”开头,因此该列表将如下所示:
const filteredList = [
{
title: 'Section One',
data: [
{
title: 'Bx',
},
{
title: 'By',
}
],
},
{
title: 'Section Two',
data: [
{
title: 'Bx',
},
{
title: 'By',
}
],
},
];
到目前为止,我尝试过的是这样的事情:
const items = list.filter(item =>
item.data.find(x => x.title.startsWith('A')),
);
或
const filtered = list.filter(childList => {
childList.data.filter(item => {
if (item.title.startsWith('B')) {
return item;
}
return childList;
});
});
但是我想我在这里缺少要点,也许你们中的一些人可以给我提示或暗示我做错了
最诚挚的问候
答案 0 :(得分:1)
您的问题是您正在BackColor
上进行White
。这将保留或删除.filter()
中的对象。但是,根据您的情况,您想将所有对象都保留在list
中,而是将它们映射到新对象。为此,您可以使用list
。这样,您可以将list
数组中的对象映射到包含过滤后的.map()
数组的新对象。这是您可能如何做的一个示例:
list