Find empty and null values in object and update in a counter javascript

Tags: , , , ,



I have the below object and I want to count the empty or null values in the object and update it in a property counter of that object.

E.g. I have this below object.

var userData = {
  firstName: "Eric",
  lastName: null,
  age: "",
  location : "San francisco",
  country: "USA",
  counter: 0
}

The result of iterating through this object would let us know that lastName and age is empty or null, so it should update counter: 2 indicating that 2 fields are empty.

obj userData = {
  firstName: "Eric",
  lastName: null,
  age: "",
  location : "San francisco",
  country: "USA",
  counter: 2
}

How can I achieve this?

Answer

You can filter through the values of the object using a Set to store all values considered empty.

const userData = {
  firstName: "Eric",
  lastName: null,
  age: "",
  location : "San francisco",
  country: "USA",
  counter: 0
};
const emptyValues = new Set(["", null, undefined]);
userData.counter = Object.values(userData).filter(x => emptyValues.has(x)).length;
console.log(userData);

We can use reduce instead of filter to minimize memory usage.

const userData = {
  firstName: "Eric",
  lastName: null,
  age: "",
  location : "San francisco",
  country: "USA",
  counter: 0
};
const emptyValues = new Set(["", null, undefined]);
userData.counter = Object.values(userData).reduce((acc,curr) => acc + emptyValues.has(curr), 0);
console.log(userData);


Source: stackoverflow