【发布时间】:2020-08-18 20:10:22
【问题描述】:
我有如下数据,
const items = [
{
id: '1',
color: 'green',
name: 'item1',
polygons: [
{
id: '1',
coordinates: [
{
latitude: '25.00',
longitude: '-25.99',
}
{
latitude: '15.00',
longitude: '-25.99',
}
{
latitude: '25.00',
longitude: '-35.99',
}
],
}
]
subItems: [
{
id: '1',
name: 'subitem-1',
color: 'green',
polygons: [
{
id: '2',
coordinates: [
{
latitude: '25.00',
longitude: '-25.99',
}
{
latitude: '15.00',
longitude: '-25.99',
}
{
latitude: '25.00',
longitude: '-35.99',
}
],
}
]
}
],
},
{
id: '2',
color: 'red',
name: 'item2',
polygons: [
{
id: '3',
coordinates: [
{
latitude: '25.00',
longitude: '-25.99',
}
{
latitude: '15.00',
longitude: '-25.99',
}
{
latitude: '25.00',
longitude: '-35.99',
}
],
}
]
subItems: [
{
id: '2',
name: 'subitem-1',
color: 'red',
polygons: [
{
id: '5',
coordinates: [
{
latitude: '25.00',
longitude: '-25.99',
}
{
latitude: '15.00',
longitude: '-25.99',
}
{
latitude: '25.00',
longitude: '-35.99',
}
],
}
]
}
],
}
]
现在我想从上面的 Items 数组中找到 ID 为“2”的子项的索引。
我尝试了类似下面的方法,
const siIndex = Items.forEach(
(item: any) =>
item.subItems ?
item.subItems.findIndex((subItem:any) => subItem.id === '2');//error here
);
但这给了我解析错误':'预期
如何从 Items 数组中找到 id = '2' 的子项的索引。有人可以帮我解决这个问题吗?
我不确定如何遍历 Items 数组并找到 ID 为“2”的 subItem 的索引。 谢谢。
【问题讨论】:
-
您没有正确使用三元运算符。请咨询this。这就是您遇到解析错误的原因。
-
您需要
find方法。看看here -
谢谢。但是您为我的代码提供了 sn-p 作为您的答案。
-
@saritha 有多个使用 array.filter 的示例,如上面的 artur 所示。请查看并尝试解决问题。
-
我没有提供您问题的答案。只需将您指向修复解析错误所需的资源,然后自行过滤。如果我想回答,我会发布答案。
标签: javascript reactjs typescript