Home > OS >  How do I check the missing fields while comparing an array and an object?
How do I check the missing fields while comparing an array and an object?

Time:12-13

I have an string array that has the name of some particular fields as shown :

const fields = [
    "FULL_NAME",
    "EMAIL_ADDRESS",
    "PHONE_NUMBER",
    "HOME_ADDRESS"
]

and the object that is supposed to store the state for these fields as :

const obj = {
    "FULL_NAME": {
        firstName: "John",
        lastName: "Doe"
    },
    "PHONE_NUMBER": ""
}

Notice how some of the fields compared to the array are missing, like "EMAIL_ADDRESS" and "HOME ADDRESS".

I want to somehow compare these two and want the function to return true only if all the fields mentioned in the 'fields' array are present in the data object 'obj' WITH SOME DATA present in them(str.length > 0).

How do I accomplish this?

CodePudding user response:

You can use Array.every function for your usecase.

const hasAllFieldsIn = (fields, obj) => {
  const keys = Object.keys(obj);
  return fields.every(item => keys.indexOf(item) >= 0 && !!obj[item]);
}

const fields = [
    "FULL_NAME",
    "EMAIL_ADDRESS",
    "PHONE_NUMBER",
    "HOME_ADDRESS"
]

const obj = {
    "FULL_NAME": {
        firstName: "John",
        lastName: "Doe"
    },
    "PHONE_NUMBER": ""
}

const obj2 = {
    "FULL_NAME": {
        firstName: "John",
        lastName: "Doe"
    },
    "PHONE_NUMBER": "",
    "EMAIL_ADDRESS": "[email protected]",
    "HOME_ADDRESS": ""
}

const obj3 = {
    "FULL_NAME": {
        firstName: "John",
        lastName: "Doe"
    },
    "PHONE_NUMBER": "837362638",
    "EMAIL_ADDRESS": "[email protected]",
    "HOME_ADDRESS": "zz"
}

console.log(hasAllFieldsIn(fields, obj))
console.log(hasAllFieldsIn(fields, obj2))
console.log(hasAllFieldsIn(fields, obj3))

  • Related