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

139
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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