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

162
Visualizações
Why does the Logical Or not work in my function

How can i modify the blow sample code to not only check for empty Keys but also null and undefined.
I tried

(obj[key] !== '' || obj[key] !== null || (obj[key] !== undefined)  

but that broke it and didnt work at all so if i use either condition it will work but not when all together. So i am wondering how i can combine it all 3 conditions in this code.

const removeEmpty = (obj) => {
  let newObj = {};
  Object.keys(obj).forEach((key) => {
    if      (obj[key] === Object(obj[key])) newObj[key] = removeEmpty(obj[key]);
    else if (obj[key] !== '')               newObj[key] = obj[key];
  });
  return newObj;
}

var obj = {
  Sale: {
    homeownerExemption: '',
    lastContractDate: '',
    lastSaleBookNumber: undefined,
    lastSaleDate: null,
    saleType: 'Full Sale',
    salesPrice: '785000',
    salesPriceCode: 'Sales Price Will Be Computed',
    seller1FName: '',
    seller1IdCode: '',
    seller1FirstName: 'Steve',
    seller1LastName: 'Miller',
    seller2FirstName: '',
    seller2LastName: '',
    transferType: 'Grant Deed',
    lastTransactionRecordingDate: '7/8/2021'
  },
  contact: [{
    name: 'Tom',
    age: '',
    sex: 'male'
  }]
};


const removeEmpty = (obj) => {
  let newObj = {};
  Object.keys(obj).forEach((key) => {
    if (obj[key] === Object(obj[key])) newObj[key] = removeEmpty(obj[key]);
    else if (!(obj[key] === "" || obj[key] === null || obj[key] === undefined)) newObj[key] = obj[key];
  });
  return newObj;
};

let test = removeEmpty(obj)

console.log(test)

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

0

If obj[key] === "", then it's not equal to null or undefined. So the second and third parts of your condition pass.

Try

if (!(obj[key] === "" || obj[key] === null || obj[key] === undefined))
about 4 years ago · Juan Pablo Isaza Relatório

0

You need to parenthesize the condition properly. Don't be cheap out on the parens, they're free! A reasonable way could be like this:

((obj[key] !== '') || (obj[key] !== null) || (obj[key] !== undefined))

Your condition has an extra ( after second ||.

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