Search code examples
javascriptarraysjavascript-objects

Object with nested array to filter, want to return entire object with new filtered array


I'm attempting to remove an object out of an array nested within my movie object and then copy it to a new variable. So my original object looks like this:

{
    "id": 1,
    "title": "Avatar",
    "movieLength": 162,
    "releaseDate": "2009-12-18",
    "trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
    "genre": {
        "id": 1,
        "genre": "Action"
    },
    "rating": {
        "id": 3,
        "rating": "PG-13"
    },
    "director": {
        "id": 1,
        "lastName": "Cameron",
        "firstName": "James"
    },
    "actors": [
        {
            "id": 2,
            "lastName": "Worthington",
            "firstName": "Sam"
        },
        {
            "id": 3,
            "lastName": "Weaver",
            "firstName": "Sigourney"
        },
        {
            "id": 4,
            "lastName": "Saldana",
            "firstName": "Zoe"
        }
    ],
    "comments": []
}

and what I'm doing right now is

const updatedMovie = const updatedMovie = movie.actors.filter((actor) => actor.id !== id);

but as you know that only returns the array of actors I filtered. I want to copy the entire object with the newly filtered actors so the object will come out like this (removing actor id 3):

{
    "id": 1,
    "title": "Avatar",
    "movieLength": 162,
    "releaseDate": "2009-12-18",
    "trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
    "genre": {
        "id": 1,
        "genre": "Action"
    },
    "rating": {
        "id": 3,
        "rating": "PG-13"
    },
    "director": {
        "id": 1,
        "lastName": "Cameron",
        "firstName": "James"
    },
    "actors": [
        {
            "id": 2,
            "lastName": "Worthington",
            "firstName": "Sam"
        },
        {
            "id": 4,
            "lastName": "Saldana",
            "firstName": "Zoe"
        }
    ],
    "comments": []
}

I've tried reading around but I'm not having any luck getting any solutions to work with me, so if anyone can help or point me in the right direction that would be great!


Solution

  • If you want to mutate the existing object, just assign the result of the .filter to the .actors property.

    movie.actors = movie.actors.filter((actor) => actor.id !== id);
    console.log(movie);
    

    If you want to keep the existing object unmutated, spread the rest of the properties into a new object while filtering.

    const updatedMovie = {
      ...movie,
      actors: movie.actors.filter((actor) => actor.id !== id)
    };
    console.log(updatedMovie);