javascript - 如何使用打字稿找到遍历对象数组的id并做出反应?
问题描述
我有如下数据,
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”的 subItems 的索引。
我尝试了类似下面的东西,
const siIndex = Items.forEach(
(item: any) =>
item.subItems ?
item.subItems.findIndex((subItem:any) => subItem.id === '2');//error here
);
但这给了我解析错误':'预期
如何从 Items 数组中找到 id = '2' 的 subItem 的索引。有人可以帮我解决这个问题。
我不确定如何遍历 Items 数组并找到 ID 为“2”的 subItem 的索引。谢谢。
解决方案
a.findIndex(b => b.subItem.id ===2)
尝试上述解决方案。这是您正在使用的列表
但我有一个解决方案/示例
你有一些结构,如 const a = [{id:'some1', subItem:{ id:1}},{id:'some2', subItem:{ id:2}}]
下面将返回 ID === 2 的 subItem 的索引
a.findIndex(b => b.subItem.id === 2);
const a = [{id:'some1', subItem:{ id:1}},{id:'some2', subItem:{ id:2}}]
//Below will return index for subItem with ID === 2
a.findIndex(b => b.subItem.id === 2);
to get both indexes
const matchedItemIndex = a.findIndex(b => b.subItem.id === 2);// return matched itemIndex
const matchedItem = a.find(b => b.subItem.id === 2);
const matchedSubItemIndex = a[matchedItemIndex].findIndex(b => b.id === matchedItem.id);// return mamtching subItemIndex
推荐阅读
- python-3.x - 如何通过 YouTube API 阻止 YouTube 搜索列表中的特定国家/地区?
- sorting - 如何使用 AQL 通过排序索引来抵消限制?
- vue.js - 什么时候将一个Vue组件拆分成多个组件(子组件)
- api-key - Quizlet API 不可用
- ios - iOS Testflight - 如何邀请个人测试人员
- c# - 更改 GridView 分页索引时是否可以防止回发?
- traefik - 使 Traefik 路由到不同端口的同一台机器上的服务
- java - 将服务文件中的 observaleList 项目添加到控制器文件中的另一个,但给出空列表
- oracle - IIS 中 mod_proxy ProxyPreserveHost 的等价物?
- javascript - 本地文件的电子 HTTPS