Home > Software engineering >  Javascript Object : check every object in array of object where value equal to
Javascript Object : check every object in array of object where value equal to

Time:03-16

Please find below general problematic regarding object iteration and queries.

Here is an object list (aimed at managing a connexion form) :

const connexionData = {
  mail: {
    value: false,
    isRequired: true
  },
  password: {
    value: false,
    isRequired: true
  },
  name: {
    value: false,
    isRequired: false
  },
}

Here is an array variable which stores all the object from connexionData const fieldstocheck = [connexionData.mail, connexionData.password, connexionData.name]

And the purpose of the function check below is to check if:

For each object in fieldstocheck where isRequired is true, if value is false, return true, or else, return false

const check = () => {
  if((fieldstocheck.filter(key => 
    key.isRequired).every(val => 
        !val.value))) {
            return true
  } else {
    return false
  }
}

This function does the job in general. With current object values, it returns true, and false if values are changed to true or to ""

But I was wondering if there would be a faster or mor elegant way of reaching the same goal.

Have a nice day everyone !

CodePudding user response:

The result you're after is a boolean, but you're currently using .filter() which creates an intermediate array. You can remove the .filter() and instead call .every() directly on fieldstocheck array to avoid creating a new array in memory. Removing the filter also does fewer iterations as you're only iterating your array once:

const connexionData = { mail: { value: false, isRequired: true }, password: { value: false, isRequired: true }, name: { value: false, isRequired: false }, }

const fieldstocheck = [connexionData.mail, connexionData.password, connexionData.name];

const res = fieldstocheck.every((obj) => !obj.isRequired || !obj.value);
console.log(res);

In the above, we first check if isRequired is false with !obj.isRequired. If it is false then the .every() callback method returns true for that object (as we're negating ! isRequired). When the first operand for || is truthy, the || short-ciruits and so we don't worry about checking right-hand side of the ||. Otherwise, if isRequired is true, we check the right-hand side of the condition to check if the obj.value is false: !obj.value.

In propsitonal logic, the above condition:

!obj.isRequired || !obj.value

is logically equivalent to

!(obj.isRequired && obj.value)

(see De Morgan's law for more details), so we could have also used this as our condition also. You could interpret this as: if the object is required and has a value, then return false, otherwise, true (if it isn't required or doesn't have a value).

  • Related