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

193
Visualizações
How to remove object property from an array of objects if the value is 0

I have an array like this:

const data = [
  { percent: 123, unit: -1 },
  { percent: 456, unit: 0 },
  { percent: 0, unit: 5},
  { percent: 789, unit: -3 }
];

and I'm trying to remove all properties that have 0 value, so the desired result will be like this:

var data = [
  { percent: 123, unit: -1 },
  { percent: 456 },
  { unit: 5},
  { percent: 789, unit: -3 }
];

I've tried something like this:

const newData = 
   data.map(e => 
      Object.keys(e).forEach(key => 
         e[key] === 0 && delete e[key]));

but that returns an array of undefined values.

const data = [
    { percent: 123, unit: -1 },
    { percent: 456, unit: 0 },
    { percent: 0, unit: 5},
    { percent: 789, unit: -3 }
];

const newData = data.map(e => Object.keys(e).forEach(key => e[key] === 0 && delete e[key]))

console.log(newData)

What am I doing wrong? Thanks in advance!

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

0

Array#forEach doesn't return an array.

To achieve your desired output, in each iteration, use Object#entries to get the key-value pairs of the current object, and Array#filter to filter the ones where the value is zero. To construct the resulting object again, use Object#fromEntries:

const data = [ { percent: 123, unit: -1 }, { percent: 456, unit: 0 }, { percent: 0, unit: 5}, { percent: 789, unit: -3 } ];

const newData = data.map(e => 
  Object.fromEntries(
    Object.entries(e).filter(([key, value]) => value !== 0)
  )
);

console.log(newData)

about 4 years ago · Juan Pablo Isaza Relatório

0

It is all undefined because you are not returning anything from the method inside data.map.

You can use Array reduce method to solve this problem.

const data = [
    { percent: 123, unit: -1 },
    { percent: 456, unit: 0 },
    { percent: 0, unit: 5},
    { percent: 789, unit: -3 }
];

const newData = data.map(e => {
  const newObj = Object.keys(e).reduce((prev, curr) => {
    if(e[curr] !== 0) prev[curr] = e[curr];
    return prev;
  }, {});
  return newObj;
})

console.log(newData)

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