根据条件创建并推送元素到新数组

4

我的数据数组

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

对于data[],我能够通过推入元素来创建一个新的数组(sportarr[]),但我希望在同一个数组sportarr[]中为competetion[]match[]也创建相同的数组。

如果有其他方法,请帮助我...

我的代码:我正在循环它:

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
    });
}
3个回答

3

如果您想根据映射创建自己的内容,我建议先遍历该数组,然后映射每个匹配和竞争,并在映射内编写自己的逻辑。

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

2

我感谢Pathikrit Sanyal和Fahd Lihidheb提供的答案。以下是根据Pathikrit Sanyal的建议所做出的更改:

  for (let i = 0; i < arrlength; i++) {
        let competition = [];
        competition = response.data[i].competetion.map((val, index) => {
          let match = [];
          match = val.match.map((value, indx) => {
            return {
              id: indx,
              value: false
            };
          });
          return {
            id: index,
            value: false,
            match
          };
        });
        this.sportarr.push({
          id: i,
          value: false,
          competetion: competition
        });
        console.log('myarrr...', this.sportarr);
      }

现在我得到了我想要的东西


1

我不确定你是否试图为每个嵌套数组(competetion和match)创建一个数组,但是这里有:

this.sportsSidebar = response.data;   // My data Array (this.sportsSidebar)


const competetionList = // Array of competetions
    [].concat.apply([], this.sportsSidebar.map(item => item.competetion));

const matchList = // Array of matchs
    [].concat.apply([], competetionList .map(item => item.match));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接