是否有辦法計算出一個嵌套物件中空屬性的總量?
[{
"name": test,
"id" : ""。
"rating": {
"title": "",
"type": "書"。
"star": 2。
}
}]
我試過Object.keys(data).length,但顯然這不能讓我找回嵌套的東西。
任何建議都會有幫助。
uj5u.com熱心網友回復:
你可以用Array.reduce()創建一個遞回函式來迭代所有的值,如果一個值也是一個物件(或陣列),就在嵌套的物件上呼叫這個函式:
const isNonNullObject = obj => typeof obj === 'object' && obj ! ==null
const countEmpty = obj =>
Object.values(obj)。
.reduce((acc, v) =>/span> {
if(v === '') return acc 1
if(isNonNullObject(v)) return acc countEmpty(v)
return acc
}, 0)
const arr = [{"name"/span>: "test","id":""," rating": {"title":"","type": "book","star":2}}]
const result = countEmpty(arr)。
console.log(result)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
使用一個遞回的reduce:
let data = [{"name"/span>: "test","id" : "","評級": {"標題": "","type": "書","星"。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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/322418.html
標籤:
上一篇:專案問題,求圖片處理建議
