【问题标题】:How to map multiple properties to arrays in Angular 6?如何将多个属性映射到 Angular 6 中的数组?
【发布时间】:2019-04-10 09:10:51
【问题描述】:

我有一个对象数组,例如:

const data: any[] = [
     { x: 1, y: 1 },
     { x: 2, y: 2 },
     { x: 3, y: 4 },
     { x: 4, y: 6 }
];

// get x as array
from(d).pipe(map(m => m.x), toArray()).subscribe(x => ...);

并希望将其映射到下面的内容以在Plotly 中使用它

{
  x: [1,2,3,4],
  y: [1,2,4,6]
}

当然,我可以复制上面的管道来获取 y 值,但这将是不同的订阅。有没有其他方法可以解决这个问题?

【问题讨论】:

    标签: angular rxjs rxjs-pipeable-operators


    【解决方案1】:

    与 RxJS 无关,它只是普通的 JS。

    使用reduce如下:

    const data = [
         { x: 1, y: 1 },
         { x: 2, y: 2 },
         { x: 3, y: 4 },
         { x: 4, y: 6 }
    ];
    
    const plotly = data.reduce((p, n) => ({ 
      x: [...p.x, n.x], 
      y: [...p.y, n.y]
    }), { 
      x: [], 
      y: []
    });
    
    console.log(plotly);

    【讨论】:

      【解决方案2】:

      让我们在这里使用一些 ES6 魔法。我们将使用spread syntaxObject.assign。在某种程度上,我们是在转置这个对象数组。

      const data = [
           { x: 1, y: 1 },
           { x: 2, y: 2 },
           { x: 3, y: 4 },
           { x: 4, y: 6 }
      ];
      
      const result = Object.assign(...Object.keys(data[0]).map(key =>
        ({ [key]: data.map( o => o[key] ) })
      ));
      
      console.log(result)

      【讨论】:

      • 哇,我得看看这个魔法里面发生了什么。但是我必须添加目标Object.assign({},... 来编译它。谢谢!
      • @alex555 是的,我承认这个可能有点难以阅读! trichetriche 的解决方案似乎是这里所有答案中最易读的!
      【解决方案3】:

      改用 rxjs reduce

      from(this.data).pipe(
        reduce((acc, m) => {
          acc.x.push(m.x);
          acc.y.push(m.y);
          return acc
        }, {x: [], y: []})).subscribe(x => console.log(x));
      

      https://stackblitz.com/edit/angular-gldpxy

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-14
        • 2014-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-11
        • 2019-05-12
        • 1970-01-01
        相关资源
        最近更新 更多