3

I need to retrieve only the object that have the name ... as a participant using a filter(pipe).

Every object has an array of participants objects. This is what it looks like(see my example Json at the end)

-object
 -- _id
 -- participants
    -- participant1
    -- participant2

So this is what I tried:(hardcoded Jack to get a match...)

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;
            }); 
        })
        )); 
  }
}

Altough this doesn't work, and I can't see the mistake I made.

I tried this to (from 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");
    })

I also saw this post but could get the right answer for me: Filtering array based on value in deeply nested object in javascript

The example 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
      }
    ]
  }
]
Ferryzijl
  • 642
  • 2
  • 8
  • 22

0 Answers0