angular - 将数组拆分为 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);
解决方案
这只不过是您的数组的减少:
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>
推荐阅读
- c# - 发送带有请求正文的http get c#
- jquery - 使用 Fullpage.js 当部分可见时我应该使用哪种方法来触发 jquery 动画?
- c# - 无法从 System.Collections.Generic.List 转换
到 System.Collections.Generic.IEnumerable - java - 如何以root身份运行java命令?
- firebase - Firebase 云在一个功能中处理多个事务?
- swift - SKRenderer 未在 MTKView 中渲染 SKShapeNode 的 alpha 通道
- sql - Vertica - 可以与 Group by 联合吗?
- javascript - 如何让 emailjs 返回成功消息?
- javascript - 不需要的括号不断从我的函数返回(JavaScript/html)
- javascript - 将视频从数据库嵌入网站