Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

276
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda