-2

I wanted to check whether a collection has value or not, I did like below and its working. Please suggest if we have any better approach...

I am checking if data is [] then do nothing, else do something

let data = await this.http.post(_postsURL, {
  headers: this.getPostAPIHeader()
}).toPromise();
if (data[0]) {
  console.log("response yes ");
} else {
  console.log("response no ");
}
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Jayesh
  • 641
  • 4
  • 13
  • 32
  • The better approach would be to check data.length. data[0] might contain a falsy value and break your check – Jonathan Jul 09 '18 at 17:04
  • Determinate if `0 === data.length`. – Chayim Friedman Jul 09 '18 at 17:05
  • `if (!data || !data.length) { console.log('empty'); } else { console.log('has values'); }` – lealceldeiro Jul 09 '18 at 17:06
  • Your text says you compare `data` to `[]`, but your code checks `data[0]` for truthiness. If you want to compare `data` to `[]` then use `if (data == [])`, although as others have noted, it's better to check the length. See [Check if array is empty / does not exist. JS](https://stackoverflow.com/q/24403732) – Heretic Monkey Jul 09 '18 at 17:10

2 Answers2

0

try this instead:

if (data.length===0 || !date) {
  console.log("response yes ");
} else {
  console.log("response no ");
}
fr97
  • 1
-1
if (data !==undefined && data.length >0) {
  console.log("response yes ");
} else {
  console.log("response no ");
}
Joon w K
  • 777
  • 1
  • 6
  • 27