-1

I have some JSON data like below:

{
  "errorCode": null,
  "message": "Success",
  "result": {

  },
  "totalRecord": 0,
  "checkAccess": true,
  "token": "fb8904acf4dbf0406ac3fd16acd9b84807d2a0e2913aecc3f39e90ca4b53161af6058ca5ee46b9877b75292e5ca9b8df969a325fa3b40c0e4acde546a431f55f6c07de8a854b9e0bf6aeba314d239267"
}   

In the JSON you can find the "result" is empty, but how can I identify it by if statement? I tried to use !== "undedined" and !==null but the statment still executes.

if(trend1_data[0].result !== 'undefined'){
    var resultone = trend1_data[0].result;
    var chartVal1 = resultone.mention30d.chartValues;
    for(var i=0; i < chartVal1.length; i++){
        vol1.push(chartVal1[i].value);//a for loop to generate value array
        Xvol1.push(chartVal1[i].date);// for xaris values e.g:date
    }
}
Anson Aştepta
  • 1,125
  • 2
  • 14
  • 38

3 Answers3

2

result is an object inside json array

Hope this will be useful

var a = [{
"errorCode": null,
  "message": "Success",
  "result": {

  },
  "totalRecord": 0,
  "checkAccess": true,
  "token": "someValue"
} 
]

alert(Object.keys(a[0].result).length)

jsfiddle

brk
  • 48,835
  • 10
  • 56
  • 78
0

if the obj is

var obj = {
  "errorCode": null,
  "message": "Success",
  "result": {

  },
  "totalRecord": 0,
  "checkAccess": true,
  "token": "fb8904acf4dbf0406ac3fd16acd9b84807d2a0e2913aecc3f39e90ca4b53161af6058ca5ee46b9877b75292e5ca9b8df969a325fa3b40c0e4acde546a431f55f6c07de8a854b9e0bf6aeba314d239267"
}   

try this

resultone = obj.result && ( Array.isArray( obj.result ) && obj.result.length ) || Object.keys(obj.result).length;

This will check obj.result in following order (second step is optional if you already know that result can only be an object not an array)

1) If obj.result exists

2) If yes, then whether it is an array and if it is an array then does it have items in it

3) If it is not an array, then does it have any keys.

resultone will be either true/false now, Now you can use it as

if ( resultone )
{
}
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
-1

Your resultone is either undefined or you should check differently with resultone < array.length

Check How do I check if a JavaScript array value is empty or null?

Community
  • 1
  • 1
Loek
  • 4,037
  • 19
  • 35