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

138
Vistas
Pushing value into array based on specific key name

I have the following array of food that has a corresponding array of recipes like this.

let book = [{
    food: "Bread",
    ingredients: [
       'wheat',
       'water',
       'eggs'
    ]
},{
    food: "Cake",
    ingredients: [
       'flour',
       'milk',
       'eggs',
       'chocolate'
    ]
}]

Lets say that a user needs to update a food in their recipe book and have an array like this

let update = [{
    food: "Bread",
    ingredients: [
       'sesame',
    ]
}];

If I wanted to update just the ingredients list how would I be able to do so?

The code that I would think to have is

for(let i = 0; i < book.length; i++){
    if(update.food === book[i].food){
       book[i].ingredients.push(update.ingredients)
    }
}

Is this on the right track? I feel like pushing like this on the book creates a new full field. Any help is appreciated.

Thank you

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Use ES6 Spred Syntax like this:

book[i].ingredients = [...book[i].ingredients, ...update[0].ingredients]

Also, consider Array.prototype.find() or Array.prototype.indexOf() instead of looping through the array yourself.

about 4 years ago · Juan Pablo Isaza Denunciar

0

This is what you can do to update the ingredients every time user wants to update the recipe.

let book = [{
    food: "Bread",
    ingredients: [
       'wheat',
       'water',
       'eggs'
    ]
},{
    food: "Cake",
    ingredients: [
       'flour',
       'milk',
       'eggs',
       'chocolate'
    ]
}]

let update = [{
    food: "Bread",
    ingredients: [
       'sesame',
    ]
}];

for (let i =0; i < book.length; i++) {
    if (update[0]['food'] === book[i]['food']) {
        book[i]['ingredients'].push(...update[0]['ingredients']); // will add all the ingredients
    }
}

console.log(book);

However, this is not efficient when you have more number of recipes. As every time user wanted to update the recipe you need to iterate the whole array and do updation(O(n)). Instead changing the DS would be good.

let book = {
    "Bread": {
    ingredients: [
       'wheat',
       'water',
       'eggs'
    ]
    },
    "Cake": {
     ingredients: [
       'flour',
       'milk',
       'eggs',
       'chocolate'
    ]
    }
};

let update = {
    "Bread": {
    ingredients: [
       'sesame',
    ]
    }
};

Object.keys(update).forEach(food => {
     const { ingredients } = update[food];
     book[food]?.ingredients.push(...ingredients);
});


console.log(book)

In the above code, you don't need to iterate through the array instead you can create an update object and run the update only once with all the updates from the user or even when a user updates the update object(on your requirement), but it is more efficient in terms of operations that you wanted to do.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Solution using Array.prototype.find()

book.find(element => element.food === update[0].food).ingredients.push(update[0].ingredients);
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