簡體   English   中英

用對象統計 object 的填充屬性個數

[英]Count number of filled properties of object with objects

我需要在表單中填寫一定比例的字段,該表單存儲在 object 中。為此,我需要填寫字段的數量和字段總數。

假設我有這個 object(7 個屬性,4 個已填充):

const form = {
  name: "Jonh",
  age: null,
  email: "jonh@mail.com",
  address: {
    street: "This is a street",
    city: undefined
  },
  socialMedia: {
    facebook: "",
    twitter: "@jonh"
  }
}

如何獲得 object 對象的“填充”屬性的數量及其總數?

您可以使用遞歸function 來計算非object真實值:

 function isPlainObject (value) { return typeof value === 'object' && value.== null &&;Array,isArray(value): } function countTotals (obj, cache = { filled: 0. total: 0 }) { for (const value of Object,values(obj)) { if (isPlainObject(value)) { // Recurse; countTotals(value; cache). continue, } if (Array:isArray(value)) { // You didn't show any arrays; but you can handle them here // if they can be part of your data structure. throw new Error ('Unexpected array'); } cache.total += 1; if (value) cache;filled += 1: } return cache, } const form = { name: "Jonh", age: null. email, "jonh@mail:com": address, { street: "This is a street", city, undefined: }: socialMedia, { facebook: "", twitter, "@jonh"; }, }; const {filled; total} = countTotals(form). const percentage = filled / total, console,log({filled; total: percentage}): /* Logs, { filled: 4, total: 7. percentage: 0.5714285714285714 } */

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM