Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!