【问题标题】:How to find the id looping through the array of objects using typescript and react?如何使用打字稿找到遍历对象数组的id并做出反应?
【发布时间】: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


【解决方案1】:
a.findIndex(b => b.subItem.id ===2)

尝试上述解决方案。这是您正在使用的列表

但我有一个解决方案/示例

你有一些结构,比如 const a = [{id:'some1', subItem:{ id:1}},{id:'some2', subItem:{ id:2}}]

下面将返回 ID === 2 的子项的索引

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 

【讨论】:

  • 您想要匹配来自 subItem 数组或 items 数组的索引?
  • 我也想同时检查 subItem 和 items 数组。
  • 那么你需要编写一个函数并保留所有匹配的索引
【解决方案2】:

正确的搜索可以这样完成:

items.findIndex((item) => item.subItems.some((sub) => sub.id == '2'))

例子:

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',
          }
        ],
      }]
    }],
  }
]

const itemIndex = items.findIndex((item) => item.subItems.some((sub) => sub.id == '2'));

console.log('Item index with subItems with id=2 is:', itemIndex)

【讨论】:

    【解决方案3】:

    您可以运行嵌套循环,或者您可以直接访问子项并使用 some 或 filter 但如果您想要完全递归,这里有一个相当冗长的要点以便解释

    const iterate = (obj) => {
      // loop through object properties
      Object.entries(obj).forEach(([key, value]) => {
        if (obj.hasOwnProperty(key)) {
          // do something with the current iteration
          
          if (typeof value === 'object') {
            // if the property value is an object then iterate into that object
            iterate(value)
          }
        }
      });
    };
    
    iterate(items);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-23
      • 2018-12-05
      • 2020-11-30
      • 2017-09-29
      相关资源
      最近更新 更多