0

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

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
stark
  • 59
  • 1
  • 7

1 Answers1

3

You can use <Array>.some

listDump.some(sheet => sheet.properties.title == newData) // returns true | false
skara9
  • 4,042
  • 1
  • 6
  • 21
  • I have changed the value of the variable, now it is in the JSON object. When I do `listDump.some(sheet => sheet.properties.title == fileName)` out `true`, but when I do `listDump.some(sheet => sheet.properties.title != fileName)` it comes out `true` too, why does this happen? How can I change the condition so that they are different? – stark Jan 25 '22 at 15:52
  • first one checks if any element has a title equal to filename, second checks if any element has a title other than filename ---- if you want to check if every element has a title other than filename replace `some` with `every` on the 2nd statement or add a not `!` to the beginning of the 1st statement – skara9 Jan 25 '22 at 16:02