¿Hay alguna forma de calcular la cantidad total de atributos vacíos dentro de un objeto anidado?
[{ "name": test, "id" : "", "rating": { "title": "", "type": "book", "star": 2 } }] Object.keys(data).length pero obviamente esto no me devuelve los anidados.
Cualquier sugerencia sería útil.
Puede crear una función recursiva con Array.reduce() para iterar todos los valores, y si un valor también es un objeto (o una matriz), llame a la función en el objeto anidado:
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)Use una reduce recursiva:
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);