简体   繁体   中英

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:

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

You can use <Array>.some

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM