簡體   English   中英

使用 map 將數組中的對象重新格式化為新元素數組

[英]Using map to reformat objects in an array to new element array

 getCardList() {
    this.http
      .get<CardList>
      (BACKEND_IP + CARD_LIST)
      .subscribe(data => {
        console.log(data);
        this.cardList = data;
        console.log(this.cardList);
        return this.cardList;
      });
    return this.cardList;
  }

我從后端得到答案:

0:
mass: (2) [25, 50]
name: "Tanks"
__proto__: Object

1:
mass: (2) [10, 15]
name: "Car"
__proto__: Object


----------

我如何獲得數組格式

mass: (25) 
name: "Tanks"

mass: (50)
name: "Tanks"

mass: (10)
name: "Car"

mass: (15)
name: "Car"

通過this.cardList.map

您可以通過flatMap方法map您想要的對象,然后是平面數據:

 const arr = [ { mass: [25, 50], name: "Tanks" }, { mass: [10, 15], name: "Car" } ]; const result = arr.flatMap(a => a.mass.map(s=> ({mass: s, name: a.name}))); console.log(result);

嘗試解決方案

  let cardList = [{mass: [25,50], name: 'tank'}, {mass: [10,15], name: 'Car'}]  

    const res =  cardList.map(({mass, name})=> {
        return mass.map(m => ({mass: m, name}))
    }).flat()
    console.log(res)

這是使用mapreduce的解決方案:

 const cardList = [ { mass: [25, 50], name: 'Tanks' }, { mass: [10, 15], name: 'Car' } ]; const out = cardList.reduce((acc, c) => { // Destructure the mass and name // from the current object const { mass, name } = c; // Create a new array of objects by mapping // over the mass array and creating a new object for each const temp = mass.map((n) => ({ mass: n, name })); // Spread out the new array and concatentate // to the accumulator return acc.concat(...temp); }, []); console.log(out);

 let list = [ {'mass': [25, 50], 'name': 'Tanks'}, {'mass': [10, 15], 'name': 'Car'} ]; let result = list.reduce((acc, o) => (acc.push(...[...o.mass.map(v => ({'mass': v, 'name': o.name}))]), acc) , []); console.log(result);

既然你用 Angular 標記了這個,我假設你正在使用 Observables 和 rxjs。 您可以使用可管道操作符,例如map ,以及mapflat 的JavaScript 操作符

getCardList() {
    return this.http
      .get<CardList>
      (BACKEND_IP + CARD_LIST).pipe(
       map(result => {
          // conversion routine borrowed for @Harish
          const newArray =  result.map(({mass, name})=> {
              return mass.map(m => ({mass: m, name}))
          }).flat()
         return newArray;
        }
      )
      .subscribe(data => {
        console.log(data);
      });
  }

我還從subscribe()內部取出了您的回報,因為 subscribes 不需要回報。 我還從方法中返回了 observable 而不是this.cardlist 因為在異步服務返回結果之前,將從此方法返回一個空數組——或未初始化的值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM