Link to home
Start Free TrialLog in
Avatar of John S.
John S.Flag for United States of America

asked on

How to remove NULL objects from my array

I have an object that has an array of another object in it. I need to remove any null ones, as pictured here.

In this example, I need my original object the way it is, but just remove the 3rd array element ( highlighted ) which is null.

Does anyone know how to iterate through this object and remove any NULL ones from my Repair array?

Thanks for your help!

Avatar of ste5an
ste5an
Flag of Germany image

Without further context, use array.filter(). E.g.

<!DOCTYPE html>
<html>
    <head>
        <script>
            (function ()
            {
                var array = [
                     { id: 1 },
                     { id: 2 },
                     null,
                     { id: 4 }
                ];

                console.log(JSON.stringify(array, null, 0));
                array = array.filter(
                    function (e) {
                        return e != undefined;
                    }
                );

                console.log(JSON.stringify(array, null, 0));
            })();
        </script>
    </head>
    <body>
    </body>
</html>

Open in new window


p.s. think about how really helpful posting images is, when you ask code related questions.. means that we cannot copy and paste from a concise and complete example..
Avatar of John S.

ASKER

Thank you for your reply. Duly noted about images.

I am new at Javascript so please bare with me. Can the above be made into a function where I can pass my object into and be returned the clean object? The syntax you used above is a bit confusing. Again, new. How would I pass my object into a function with no arguments expected?  ( I am sure that is a complicated answer, but I'd like to just get a working version ). Thank you again for your very quick post.
ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of John S.

ASKER

Works perfect. Thank you for your assistance.