Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if the value of a variable exists in an object

I have a Typescript project where I need to know if the value of a variable is in any property of the Object.

This is the object:

let listDump = [
   {
     "properties":{
        "title":"CARS"
     }
  },
  {
     "properties":{
        "title":"HOME"
     }
  },
  {
     "properties":{
        "title":"COUNTRY"
     }
  }
];

This is the declared variable:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let newData = 'ANIMALS'

This is what I do to check if it exists:

for (let sheet of listDump) {
  if (sheet.properties.title == newData) {
    console.log(`do not create property`)
  } else {
    console.log('create property') 
  }
}

Problem: Doing three checks operates three times on the else

What I need to know is how to check that it exists without needing to iterate over the object and operate only once in case it doesn’t exist

>Solution :

You can use <Array>.some

listDump.some(sheet => sheet.properties.title == newData) // returns true | false
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading