Home > Mobile >  If statements are not working in using javascript or jsx
If statements are not working in using javascript or jsx

Time:10-08

Having issues to get code block to log to console

Does not work. Nothing is logged to console

var data = {"_id": "615fc3db8b6a6311aa3295ca", "isComplete": false, "remindTime": {"date": "2021-10-08", "time": "12:08:40 am"}, "subtitle": "Fdfdff", "title": "Dfdf"}

if (data.length > 0) {
    console.log('my data', data);
}

WHAT WORKS:

var data = {"_id": "615fc3db8b6a6311aa3295ca", "isComplete": false, "remindTime": {"date": "2021-10-08", "time": "12:08:40 am"}, "subtitle": "Fdfdff", "title": "Dfdf"}

if (data.title) {
    console.log('my data', data);
}

Not sure what's going wrong

CodePudding user response:

You are testing for a length property on an plain js object that you have not explicitly placed a length property on.

Testing for a length seems like you're expecting it to be an array.

It would be similar to running this in the console, you'll get undefined.

({}).length

If you'd like to log it if it is an object:

if (data) {
    console.log('my data', data);
}

If you'd like to log it if it has any properties on it:

if (Object.keys(data).length) {
    console.log('my data', data);
}

CodePudding user response:

in your case - data is not an array, it is an object. You got to use Object.keys(data).length to find no of keys in an object. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

CodePudding user response:

Object does not have any length property. If you want to check the existence of the object, just write this:

if (data) {
    // executable code
}

it will check if the object has any property or not.

  • Related