Search code examples
javascriptarraysreactjsobjectis-empty

For empty object giving the TypeError: Cannot convert undefined or null to object


Well, I know this is would be a very common question but I tried to find the solution but no luck yet. So here is the problem statement :

Due to some condition, my object is having no values and it is empty {} and when I try to check the length of this object using Object.keys(ambassador).length OR Object.entries(ambassador).length it is giving me the error

TypeError: Cannot convert undefined or null to object.

Code sample:

const ambassador = Array.isArray(ambassadors) 
        ? ambassadors.find((item) => {
                return item.affiliate_id === affiliate.tracking_id;
            })
        : {};

console.log(ambassador == null); //false
console.log(typeof(ambassador)); // Object
console.log(Object.keys(ambassador).length > 0 ); //TypeError: Cannot convert undefined or null to object.

Solution

  • So, I got solution from the comment of Kireeti Ganisetti, He suggested to use LOADASH and it worked :)

    To check if the object is empty in Javascript - React :

    import _ from 'lodash';
    _.isEmpty(ambassador)