Md Ali
Md Ali

Reputation: 247

Cannot convert undefined or null to object in javascript

I have already a write function I am stacking one error. I can't understand why this error occurring. Please help me here-

const Object11 = {
  name: 'Walton Business Class Soundless High Speed Niico Fan - Mint - 9 Inch',
  category: '630c5db82cc1c55ae7cde3a3',
  subCategory: [],
  brand: '630c5e382cc1c55ae7cde3d5',
  unit: 'Pcs',
  tag: [],
  refundAble: false,
  productImages: [
    {
      url: 'https://nekmart.s3-ap-southeast-1.amazonaws.com/Products/l7ugtc2f202289183910167l7ugtc2g.jpeg'
    }
  ],
  youtubeLink: null,
  price: 23235,
  flash: '',
  discount: 23,
  discountUnit: 'flat',
  quantity: 23,
  description: '<p></p>\n',
  attributes: [],
  visibility: true,
  meta: { title: '', description: '' },
  showStock: true,
  tax: 0,
  taxUnit: 'flat',
  disclaimer: 'The actual color of the physical product may slightly vary due to the deviation of lighting sources, photography or your device display settings. Delivery charges may vary as per the location, Product Size and Weight; we will notify before proceeding the delivery.'
}

And then I write this function-

function rec(obj) {
    for (let key of Object.keys(obj)) {
        if (obj[key] === '') {
            delete obj[key];
        } else if (typeof obj[key] === 'object') {
            obj[key] = rec(obj[key]);
            // if (obj[key] && Object.keys(obj[key]).length === 0) delete obj[key];
            console.log(Object.keys(obj[key]))
        }
    }
    return Array.isArray(obj) ? obj.filter(val => val) : obj;
}

I call this function with that object-

const productUpdateInput = rec(productUpdateInput);

But I am getting this error- Cannot convert undefined or null to object

Error throws from this line-

if (obj[key] && Object.keys(obj[key]).length === 0) delete obj[key];
console.log(Object.keys(obj[key]))

But I can't understand what is the problem. Why I am getting this type of error.

**Note- When I put above object then I found this error otherwise not.

Upvotes: 0

Views: 2442

Answers (1)

Yanick Rochon
Yanick Rochon

Reputation: 53531

  1. Your object contains a null value (i.e. youtubeLink: null,)
  2. Then you call the rec function with obj[key] = rec(obj[key]); where key === 'youtubeLink', which is rec(null).
  3. Then the rec functions tries to do Object.keys(obj), or Object.keys(null), which throws an error.

One solution would be to shortcut the function if obj is null or undefined.

function rec(obj) {
    if (obj === null || obj === undefined) return obj;
    for (let key of Object.keys(obj)) {
        if (obj[key] === '') {
            delete obj[key];
        } else if (typeof obj[key] === 'object') {
            obj[key] = rec(obj[key]);
            // if (obj[key] && Object.keys(obj[key]).length === 0) delete obj[key];
            console.log(Object.keys(obj[key]))
        }
    }
    return Array.isArray(obj) ? obj.filter(val => val) : obj;
}

UPDATE: if you want to clean the object of any empty values, then do not re-invent the wheel (unless you are doing an educational exercise), and use an existing module that has been tested for that purpose. For example clean-deep, remove-empty, etc.

Upvotes: 1

Related Questions