我只需要使用过滤器(管道)检索具有名称的对象...作为参与者。
每个对象都有一个参与者对象数组。这就是它的样子(最后参见我的Json示例)
-object
-- _id
-- participants
-- participant1
-- participant2
所以这就是我的尝试:(硬编码杰克得到一场比赛......)
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({ name: 'filter' })
export class Gamefilter implements PipeTransform {
public transform(values: any[], filter: string): string {
if (!values || !values.length) "";
if (!filter) return JSON.parse(JSON.stringify(values));
return JSON.parse(JSON.stringify(
values.filter((element) => {
return element.participants.filter((item)=> {
return item.name.indexOf("Jack") > 1;
});
})
));
}
}
虽然这不起作用,但我无法看到我犯的错误。
我尝试过(来自Filtering array of objects with arrays based on nested value):
values.filter((element) =>
element.participants.some((subElement) => subElement.name === "Jack"))
.map(element => {
let newElt = Object.assign({}, element); // copies element
return newElt.participants.filter(subElement => subElement.name === "Jack");
})
我也看过这篇文章,但可以为我找到正确的答案:Filtering array based on value in deeply nested object in javascript
示例JSON:
[
{
"_id": "5925ae95675e19001106e940",
"createdOn": "2017-05-24T16:02:29.229Z",
"participants": [
{
"_id": "jack19302",
"name": "Jack",
"__v": 0
},
{
"_id": "donald38902",
"name": "Donald",
"__v": 0
}
]
},
{
"_id": "5925ae95675e19001106e990",
"createdOn": "2017-05-24T16:02:29.229Z",
"participants": [
{
"_id": "donald38902",
"name": "Donald",
"__v": 0
}
]
},
{
"_id": "5925ae95675e19001106e996",
"createdOn": "2017-05-24T16:02:29.229Z",
"participants": [
{
"_id": "jack19302",
"name": "Jack",
"__v": 0
}
]
}
]