Nested array, return only user who is approved

I have output from backend like this.

 [
            {
                "id": 23,
                "who": [
                    {
                        "id": 1,
                        "user": {
                            "id": 9,
                            "username": "zorro",
                            "first_name": "Richard",
                            "last_name": "Zorro",
                            "avatar": "http://localhost:8000/media/default.png",
               
                        },

                        "approved": false
                    },
                    {
                        "id": 2,
                        "user": {
                            "id": 10,
                            "username": "mis2",
                            "first_name": "m",
                            "last_name": "s",
                            "avatar": "http://localhost:8000/media/default.png",
                        },
  
                        "approved": true
                    }
                ],
                "approved_looking": true,
                "who_add": 1
            }
        ],

im trying to return only user who is approved.
i have this code but it’s return all users(two).. why?

        filteredUsers() {
            if (this.users) { 
                const filt = this.users.filter(x => x.who.filter((y) => {return y.approved === true}));
                return filt
}
        },

I wonder why it works like this

>Solution :

Since you are using two filters and the output is in the first filter level. Your inner filter is not working as you expect. It returns a JSON when finding an approved one and the first level filter considers it as true and you get the whole outer object, not the inner ones.

Try like this:

const input = [ { id: 23, who: [ { id: 1, user: { id: 9, username: "zorro", first_name: "Richard", last_name: "Zorro", avatar: "http://localhost:8000/media/default.png", }, approved: false, }, { id: 2, user: { id: 10, username: "mis2", first_name: "m", last_name: "s", avatar: "http://localhost:8000/media/default.png", }, approved: true, }, ], approved_looking: true, who_add: 1, }, ];

const filteredUsers = (input) =>  {
  if (input) { 
      const filt = input.reduce((prev, curr) => {
        prev = prev.concat(curr.who.filter((y) => {return y.approved === true}))
        return prev
      }, [])
      return filt
  }
}

console.log(filteredUsers(input))

Using Array.prototype.reduce()

Leave a Reply