-2

lets assume i have data now i want to check if index is there and process the logic based on that condition, what would be correct approach using ES6 to run below conditions ?

Any better way to achieve this task ?

main.ts

data = [
  {"obj1":"data"},
  {"obj2": "data"},

  ]

if(data[0].length) {
    // process logic 
}

if(data[1].length) {
    // process logic 
}
hussain
  • 6,587
  • 18
  • 79
  • 152
  • How about _looping_? – Ram Oct 02 '18 at 17:45
  • If its the same logic you can just use a foreach loop... or for of loop (or simple for/while loop) – chevybow Oct 02 '18 at 17:45
  • Is this different logic in each case or should you do the same thing for each value that matches? Also, are you checking if the object has a `length` property or is that something else? – VLAZ Oct 02 '18 at 17:45
  • @undefined can anyone provide example how i would do that – hussain Oct 02 '18 at 17:49
  • What...write a basic loop? – VLAZ Oct 02 '18 at 17:52
  • @vlaz just want to check if response `data[0]` has object there then do the rest of the logic – hussain Oct 02 '18 at 17:52
  • Possible duplicate of [How do I check in JavaScript if a value exists at a certain array index?](https://stackoverflow.com/questions/2672380/how-do-i-check-in-javascript-if-a-value-exists-at-a-certain-array-index) – Heretic Monkey Oct 02 '18 at 17:57

2 Answers2

0

not really sure what exactly you want to do, but i think map/forEach work...

data = [
  {"obj1":"data"},
  {"obj2": "data"},

]
data.map((el, i) => { return i%2 == 0? Object.keys(el) : null })
Charlie
  • 183
  • 2
  • 14
0

I think you want to check if the data array contains valid object type values and has some key->value pair in it. If so, do it in this way

for(let value of data){
  // may ignore few checks if required
  if(value && typeof(value) === 'object' && Object.keys(value).length){
    // value is valid and is object type with some value
    // write your logic here
  }
}