Home > Back-end >  How do I add a new element in a dictionary in JS?
How do I add a new element in a dictionary in JS?

Time:06-08

I have this kind of dictionary: INPUT

movies = {
        'big' : {
            actors : ['Elizabeth Perkins', 'Robert Loggia']
        },
        'forrest gump' : {
            actors : ['Tom Hanks', 'Robin Wright', 'Gary Sinise']
        },
        'cast away' : {
            actors : ['Helen Hunt', 'Paul Sanchez']
        }
    };

and I want to use this dictionary to get a different one. For example, I have to make a function called "moviesWithActors" that will received two arguments: "movies" and "actor". Actor could be "Tom Hanks", so when you find that he was on the movie, you don't add to the nested array, but if wasn't, you add.

OUTPUT

movies = {
        'big' : {
            actors : ['Elizabeth Perkins', 'Robert Loggia', 'Tom Hanks']
        },
        'forrest gump' : {
            actors : ['Tom Hanks', 'Robin Wright', 'Gary Sinise']
        },
        'cast away' : {
            actors : ['Helen Hunt', 'Paul Sanchez', 'Tom Hanks]
        }
    };

I do this:

for (const value of Object.values(newMovies)){
    console.log(value.actors)
    for (const act of value.actors){
        //console.log(act)
        if (act == actor) {
            console.log("Ok, not add")
        }else{
            console.log("Here I have to add");
        }
    }
}

where "newMovies" is a copy of "movies" and "actor = "Tom Hanks" but I can't add to the array in actors: [ ... ]. Any suggestion? Can I use map() ?

CodePudding user response:

You can use Push()

Like this from docs

let sports = ['soccer', 'baseball']
let total = sports.push('football', 'swimming')

console.log(sports)  // ['soccer', 'baseball', 'football', 'swimming']
console.log(total.length)   // 4

To access array inside dictionary you have first to access it

movies['big']['actors'].push('New Actor')

CodePudding user response:

You can use Object.entries to create an array of the entries in movies, then conditionally add the actor to the actors list if none/any of the actors are the specified actor, then finally use Object.fromEntries to create the result object:

const movies = {
  'big': {
    actors: ['Elizabeth Perkins', 'Robert Loggia']
  },
  'forrest gump': {
    actors: ['Tom Hanks', 'Robin Wright', 'Gary Sinise']
  },
  'cast away': {
    actors: ['Helen Hunt', 'Paul Sanchez']
  }
};

const moviesWithActors = (movies, actor) => Object.fromEntries(
  Object.entries(movies)
  .map(([movie, { actors }]) => [
    movie,
    { actors: [...actors, ...!actors.includes(actor) ? [actor] : []] }
    ]
  )
)

console.log(moviesWithActors(movies, 'Tom Hanks'))

  • Related