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

147
Visualizações
How to delete a Javascript object element?

I'm using the following code to update any given property inside a JS object:

var main = {
          items: [
                  {
                    "name": "T-Shirt",
                    "description": "Green XL",
                    "quantity": "1",
                  },
                  {
                    "name": "Shoes",
                    "description": "Running, Size 10.5",
                    "quantity": "2",
                  }
                ]
        };

let project = main.items.find((p) => {
    return p.name === 'Shoes';
});

project.quantity = '3';
console.log(main); //shoes quantity is now 3

And it works, however, i want it to also be able to delete the whole project variable (for example, the whole Shoes block). I tried:

let project = main.items.find((p) => {
    return p.name === 'Shoes';
});
delete project;

console.log(main); //shoes still exist

But it doesn't work. What would be the best way to delete the property?

Edit: My main issue here was about finding the index of the element to be deleted. The chosen answer below provides the solution.

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

0

You can use Array#filter.

main.items = main.items.filter(p => p.name !== 'Shoes');
about 4 years ago · Juan Pablo Isaza Relatório

0

You cannot use the delete operator like this. To remove the found item from the array in-place, you will want to use Array#splice()

const foundIndex = main.items.findIndex((p) => {
  return p.name === 'Shoes';
});

if (foundIndex !== -1) main.items.splice(foundIndex, 1)
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