Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

280
Visualizações
How do I add a new element in a dictionary in JS?

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() ?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

As per the requirement what I understood is that there is an existing array of movies object and you want to assign a hero in those movies. We have to ignore if the passed hero name is already there for that movie else add that hero under that movie. If my understanding is correct, Here you go :

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

function updateMoviesList(obj, heroName) {
    Object.keys(obj).forEach(key => {
    if (!obj[key].actors.includes(heroName)) {
        obj[key].actors.push(heroName)
    }
  })
  return obj;
}

console.log(updateMoviesList(movies, 'Tom Hanks'));

about 4 years ago · Juan Pablo Isaza Relatório

0

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')

For not be "hard coded", if you do this?

let actor = 'Tom Hanks'
for (const value of Object.values(newMovies)){
    for (const act of value.actors){
        if (value.actors.includes(actor)) { //Here you check if actor contains in array
            console.log("Ok, not add")
        }else{
            console.log("Here I have to add");
            value.actors.push(actor) //if not push to array          
            }
        }
    }
about 4 years ago · Juan Pablo Isaza Relatório

0

I was suggested to use map instead and the class Object...

function actorInMovies(movies, actor) {
    let mappedObject = { ...movies};
    Object.entries(movies).map(movie => {
        const movieName = movie[0];
        const actors = movie[1].actors;
        if (!actors.includes(actor))
          actors.push(actor);
        mappedObject = {
          ...mappedObject,
          [movieName]: { actors }
        };
      });
    return mappedObject
}

function main(){
    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 actor = 'Tom Hanks';
    console.log(actorInMovies(movies, actor))
}

main();

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda