首页 > 解决方案 > 在新数组中创建和推送元素取决于条件

问题描述

我的数据数组

data:[
0:{ 
   id:1 ,.....
   competetion:[ 
          0:{
              id: 1....,
              match:[ 
                      0:{id: 1 ......}, 
                      1:{same}
                      .
                      .
                    ]
          1:{same}]},
          2:{same}
          .
          .
        ]
  },
1:{same},
2:{same}
.
.
.
] 

因为data[]我能够创建一个sportarr[]带有推送元素的新数组(),但我想在同一个数组中创建相同competetion[]match[]数组sportarr[] 如果有其他方法可以帮助我...

我的代码:我在这里循环它:

this.sportsSidebar = response.data;   // My data Array (this.sportsSidebar)
const arrlength = response.data.length; 
for (let i = 0; i < arrlength; i++) {
    this.sportarr.push({       // I declared a new array where i want to push the element
      id: i,
      value: false
    });
}

标签: arraysangulartypescriptfor-loopmultidimensional-array

解决方案


如果您想要基于映射的自己的内容,我建议首先遍历数组,然后映射每个匹配和竞争,并在地图中编写您自己的逻辑

 const arrlength = data.length;
      for (let i = 0; i < arrlength; i++) {
        let competition = [];
        competition = data[i].competetion.map( (val, index) => {
          #write your own logic to produce the required outcome
          return {
              id: index,
              value: false
          };
        });
        this.sportarr.push({
          id: i,
          value: false,
          competetion: competition
        });
        console.log('myarrr...', this.sportarr);

推荐阅读