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.

2

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.