0

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.

1 Answer 1

1
  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.

Sign up to request clarification or add additional context in comments.

4 Comments

I also want to be delete if object key will null or undefined
@MdAli see my updated answer.
clean-deep, remove-empty doesn't support typescript. Is there any with typescript?
@MdAli what do you mean it "doesn't support typescript"? Are you using npm or yarn to add the package to your project, and aren't you doing import clean from 'clean-deep'; ? Node modules do not need to be TypeScript, and clean-deep does have a .d.ts file declaring it's interface.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.