1

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?

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

Comments

1

You can use the function Objec.values for accessing the values of the object and the function Array.prototype.reduce for counting the empty values.

const userData = {  firstName: "Eric",  lastName: null,  age: "",  location : "San francisco",  country: "USA",  counter: 0},
      emptyValues = ["", null];
      
userData.counter = Object.values(userData).reduce((r, c) => r + emptyValues.includes(c), 0);
console.log(userData);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.