Home > Net >  Count number of filled properties of object with objects
Count number of filled properties of object with objects

Time:12-30

I need to make a percentage of fields filled in a form, which is stored in an object. For that I need the number of filled fields and the total number of fields.

Let's say I've this object (7 properties, 4 filled):

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

How can I get the number of "filled" properties of an object with objects and the it's total?

CodePudding user response:

You can use a recursive function to count the non-object, truthy values:

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: "[email protected]",
  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
}
*/

  • Related