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

120
Visualizações
Find length of empty attributes in nested JavaScript object

Is there way to calculate the total amount of empty attributes within a nested Object?

[{
  "name": test,
  "id" : "",
  "rating": {
    "title": "",
    "type": "book",
    "star": 2
  }
}]

I've tried Object.keys(data).length but obviously this doesn't give me back the nested ones.

Any suggestions would be helpful.

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

0

You can create a recursive function with Array.reduce() to iterate all values, and if a value is an object (or array) as well, call the function on the nested object:

const isNonNullObject = obj => typeof obj === 'object' && obj !== null

const countEmpty = obj =>
  Object.values(obj)
    .reduce((acc, v) => {     
      if(v === '') return acc + 1
      
      if(isNonNullObject(v)) return acc + countEmpty(v)
      
      return acc
    }, 0)


const arr = [{"name":"test","id":"","rating":{"title":"","type":"book","star":2}}]

const result = countEmpty(arr)

console.log(result)

about 4 years ago · Juan Pablo Isaza Relatório

0

Use a recursive reduce:

let data = [{"name": "test","id" : "","rating": {"title": "","type": "book","star": 2}}];

let count = data.reduce(function recur(sum, obj) {
    return sum + (obj === ""
                  || Object(obj) === obj 
                     && Object.values(obj).reduce(recur, 0));
}, 0);

console.log(count);

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