Checking if object is empty doesn't work

July333 picture July333 · May 7, 2018 · Viewed 24.6k times · Source

I am testing the case if my object was empty, so intentionally I made a query that has no match in the database, which should evaluate my else if statement however I don't get any response in the console.

What am I doing wrong?

user.loginUser = (jUserData, res) => {
    var aData = [
        jUserData.email,
        jUserData.mobile_number,
        0
    ]
    var sQuery = 'SELECT * FROM users WHERE email = ? AND mobile_number = ? AND active = ?'

    function isEmpty(obj) {
        for (var key in obj) {
            if (obj.hasOwnProperty(key))
                return false;
        }
        return true;
    }
    db.each(sQuery, aData, function (err, jRow) {
        console.log(jRow)
        if (err) {
            console.log('BAD, user not logged in')
            return res(true, {
                status: "INTERNAL SERVER ERROR"
            })
        }
        if (isEmpty(jRow)) {
            console.log('NOT FOUND')
            return res(true, {
                status: "NOT FOUND"
            })
        }
        console.log('GREAT, user logged in')
        return res(false, jRow)
        console.log(jRow)
    })
}

Answer

Arif Khan picture Arif Khan · May 7, 2018

You may like to use Object.keys() or other Object function, this code may help you

function isEmpty(obj) {
    return !obj || Object.keys(obj).length === 0;
}