首页 > 解决方案 > 将数组拆分为 Observable 中的值小块

问题描述

我挣扎了几个小时来用 Observable 在一组对象上复制一个过程,但我没有任何运气来完成它!

想象一下,我们有一个像这样的大数组作为 Observable:

[ 
  {name: "you1", id: 32}, 
  {name: "you2", id: 12}, 
  {name: "you3", id: 22},
  {name: "you4", id: 54}, 
  {name: "you", id: 09},
  {name: "you", id: 43}, 
  ....
]

并且您想将它们按 3 个数组分组,每个数组有 2 个项目,如下所示:

[ 
  [{name: "you1", id: 32}, {name: "you2", id: 12}], 
  [{name: "you3", id: 22}, {name: "you4", id: 54}], 
  [{name: "you", id: 09}, {name: "you", id: 43}], 
  ....
]

这个范围是动态的,我们需要进行一些计算并将 Observable 值转换为这种形式。好吧,我在 Javascript 中很容易完成,但我不知道如何在 RXJS 中完成。有什么帮助吗?

在 JS 中是这样完成的:

        let positionArray,
            positionItem = 0;
        const totalArray = this.groupedBySize > 0 ? Math.floor(size(this.selectedWorkspaces) / this.groupedBySize) : 0;
        this.selectedGroupedWorkspaces = [];

        for (positionArray = 0; positionArray < totalArray; positionArray += 1) {
            this.selectedGroupedWorkspaces[positionArray] = this.selectedWorkspaces.slice(
                positionItem,
                positionItem + this.groupedBySize
            );
            positionItem = positionItem + this.groupedBySize;
        }
        if (positionArray < totalArray || positionArray === 0) {
            this.selectedGroupedWorkspaces[positionArray] = this.selectedWorkspaces.slice(positionItem);
        }

        this.workspaces$ = of(this.selectedGroupedWorkspaces);

标签: angularrxjs

解决方案


这只不过是您的数组的减少:

const data = new rxjs.BehaviorSubject([ 
  {name: "you1", id: 32}, 
  {name: "you2", id: 12}, 
  {name: "you3", id: 22},
  {name: "you4", id: 54}, 
  {name: "you", id: 09},
  {name: "you", id: 43}, 
]);

const grouped = data.pipe(rxjs.operators.map(arr => arr.reduce((p, n) => {
  
  const last = p[0];
  if (last.length < 3) last.push(n);
  else p.unshift([n]);
  
  return p;
}, [[]]).reverse()));

grouped.subscribe(d => console.log(d));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js"></script>

你甚至可以创建一个自定义的 rxjs 操作符:

const data = new rxjs.BehaviorSubject([ 
  {name: "you1", id: 32}, 
  {name: "you2", id: 12}, 
  {name: "you3", id: 22},
  {name: "you4", id: 54}, 
  {name: "you", id: 09},
  {name: "you", id: 43}, 
]);

const groupArrayByGroupOf = length => rxjs.operators.map(arr => arr.reduce((p, n) => {
  
  const last = p[0];
  if (last.length < length) last.push(n);
  else p.unshift([n]);
  
  return p;
}, [[]]).reverse())

const grouped = data.pipe(groupArrayByGroupOf(3));

grouped.subscribe(d => console.log(d));
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js"></script>


推荐阅读