How to find the id looping through the array of objects using typescript and react?

后端 未结 3 1237
广开言路
广开言路 2021-01-29 11:17

i have data like below,

const items = [
    {
        id: \'1\',
        color: \'green\',
        name: \'item1\',
        polygons: [
            {
                     


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-29 11:47

    The correct search can be done like this:

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

    Example:

    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)

提交回复
热议问题