Home > front end >  Find length of empty attributes in nested JavaScript object
Find length of empty attributes in nested JavaScript object

Time:09-21

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.

CodePudding user response:

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)

CodePudding user response:

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);

  • Related