gpt4 book ai didi

javascript - 在 Angular 5+ 中过滤和/或分组数据

转载 作者:行者123 更新时间:2023-12-01 01:44:41 25 4
gpt4 key购买 nike

不幸的是,我无法控制 API 如何返回数据。我得到了我得到的:/

我需要帮助正确设置数据格式,或者可能使用自定义管道来正确显示数据。我尝试过不同的东西(mergeMap、过滤器、按管道分组等),但我似乎无法完全得到我想要的东西。任何帮助将不胜感激。

示例数据

[
{ "id": "rossbo01", "first": "Bob", "last": "Ross", "photo": "photo1.jpg", "photoTitle": "Photo1"},
{ "id": "rossbo01", "first": "Bob", "last": "Ross", "photo": "photo2.jpg", "photoTitle": "Photo2"},
{ "id": "rogersfr02", "first": "Fred", "last": "Rogers", "photo": "photo55.jpg", "photoTitle": "Photo55"},
...
]

组件

this.searchService.getData().subscribe(searchResults => {
this.searchResults = searchResults;
....? transform data here or custom pipe in template
});

期望的结果(显示一次名称,然后显示所有关联的照片)

Bob Ross
Photo1
Photo2
Fred Rogers
Photo55
...

获得我正在寻找的输出的最有效方法是什么?提前致谢!

最佳答案

以下代码是我的纯 RxJS 解决方案:P

import { from } from 'rxjs';
import { groupBy, mergeMap, map, toArray, tap } from 'rxjs/operators';

let searchResults = [
{ "id": "rossbo01", "first": "Bob", "last": "Ross", "photo": "photo1.jpg", "photoTitle": "Photo1"},
{ "id": "rossbo01", "first": "Bob", "last": "Ross", "photo": "photo2.jpg", "photoTitle": "Photo2"},
{ "id": "rogersfr02", "first": "Fred", "last": "Rogers", "photo": "photo55.jpg", "photoTitle": "Photo55"}
];

from(this.searchResults).pipe(

// Select necessary attributes
map(result => {
//console.log('Result:', result);
let fname = result['first'];
let lname = result['last'];
let photo = result['photoTitle'];
let rname = [fname, lname].join(' ');
return { rname, photo };
}),

// group objects by `rname` attribute
groupBy(result => result['rname']),

// return each item in group as array
mergeMap(group => {
//console.log('Group $1:', group);
return group.pipe(
toArray(),
);
}),

// Reduce arrays of objects
map(group => {
//console.log('Group $2:', JSON.stringify(group));
let rname = group[0]['rname'];
return group.reduce((a, b) => {
return {
rname: rname,
photo: [a.photo, b.photo],
};
});
}),

// Bypass and verify results
tap(result => console.log('Result:', result)),

).subscribe();

关于javascript - 在 Angular 5+ 中过滤和/或分组数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52062014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com