javascriptangularjslinq.js

Filter Sub array


i am trying to filter my array which has a sub array. i want to filter my array by sub array my array looks like this:

 var Branches = [
            {
                Name: 'branch1',
                Screens: [
                    {
                        Name: 'Screen1',
                        Player: {
                            Status: 0
                        }
                    },
                    {
                        Name: 'Screen2',
                        Player: {
                            Status: 1
                        }
                    }
                ]
            },
            {
                Name: 'branch2',
                Screens: [
                    {
                        Name: 'Screen1',
                        Player: {
                            Status: 0
                        }
                    },
                    {
                        Name: 'Screen2',
                        Player: {
                            Status: 1
                        }
                    }
                ]
            }]

i've tried this using linq.js

var param = 1
var result = Enumerable.From(Branches).Where(function (d) {

                return (d.Screen.some(x => x.Player.Status === param))

            }).ToArray();

but this code olso gets the status 0 from each branches

i want to get only the status = 1 from each branches

Expected out :

[
            {
                Name: 'branch1',
                Screens: [
                    {
                        Name: 'Screen2',
                        Player: {
                            Status: 1
                        }
                    }
                ]
            },
            {
                Name: 'branch2',
                Screens: [
                    {
                        Name: 'Screen2',
                        Player: {
                            Status: 1
                        }
                    }
                ]
            }

        ]

Thanks ;)


Solution

  • You could map the objects and filter Screens.

    var branches = [{ Name: 'branch1', Screens: [{ Name: 'Screen1', Player: { Status: 0 } }, { Name: 'Screen2', Player: { Status: 1 } }] }, { Name: 'branch2', Screens: [{ Name: 'Screen1', Player: { Status: 0 } }, { Name: 'Screen2', Player: { Status: 1 } }] }],
        wanted = 1,
        result = branches.map(({ Screens, ...o }) => ({ ...o, Screens: Screens.filter(({ Player: { Status } }) => Status === wanted) }));
    
    console.log(result);