Search code examples
javascriptarraysreducedestructuring

Delete null or undefined attributes in object


I want to create a method to delete null and undefined attributes.

To do that :

I convert my plain object into table

loop on it

filter on attributes if there are null or undefined

But the thing is I don't arrive to restructure my object with the new values. Let's take a look :

var req = {
    adtForm1: {
      firstName: 'John',
      lastName: undefined,
      middleName: ''
    },
    adtForm2: {
      firstName: null,
      lastName: 'Doe',
      middleName: ''
    }
  };

  removeUndefinedFormsAttributes = (somesForms) => {
    const forms = Object.values(somesForms);
    const formsUpdate = {};
    forms.forEach(item => {
      const formFields = Object.values(item);
      formFieldsKeys = Object.keys(item);
      const formFiltered = formFields.filter(field => { return field !== null && field !== undefined; });
      console.log("formFiltered", formFiltered);
    })
    console.log(somesForms)
    return forms;
  };

removeUndefinedFormsAttributes(req)

As we can see in the snippet, formFiltered change the good values but I need to return the same object as somesForms. This is what I need :

expectedValue = {
    adtForm1: {
        firstName: 'John',
        middleName: ''
    },
    adtForm2: {
        lastName: 'Doe',
        middleName: ''
    }
}

I know I need to use reduce() function and keys() function but truly I don't know how. I will really appreciate any help.


Solution

  • You can recursively iterate the object and create a new object without null or undefined. Use Object.entries() to get the keys and value pairs from the object. Iterate the pairs with Array.reduce. Ff a value is null or undefined skip it's key. If it's an object assign the result of calling removeUndefinedFormsAttributes on the value to the key. And if it's not an object just assign the value to the key.

    const req = {"adtForm1":{"firstName":"John","middleName":""},"adtForm2":{"firstName":null,"lastName":"Doe","middleName":""}};
    
    const removeUndefinedFormsAttributes = (obj) => 
      Object.entries(obj).reduce((r, [k, v]) => {
        if(v === null || v === undefined) return r;
        if(typeof v === 'object') r[k] = removeUndefinedFormsAttributes(v);
        else r[k] = v;
        
        return r;
      }, {});
    
    const result = removeUndefinedFormsAttributes(req)
    
    console.log(result)