1

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.

8245734589
  • 47
  • 5

2 Answers2

1

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)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
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);
trincot
  • 317,000
  • 35
  • 244
  • 286