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

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

i have data like below,

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


        
3条回答
  •  北恋
    北恋 (楼主)
    2021-01-29 11:27

    You can run nested loops, or you can access the subitems directly and use some or filter but if you wanted full recursion here's a fairly verbose gist for the sake of explaining

    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);
    

提交回复
热议问题