JavaScript Delete null or undefined attributes in object javascript delete null undefined

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)
Answer:1

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)
Answer:2

If you just need to remove keys with null or undefined values from objects nested one level down, then you can iterate over the values of your main object using Object.values, then iterate over the keys of each nested object using Object.keys, and delete those that match your conditions. You can test the values of your nested objects to determine if they are null or undefined with something like value == null (see How to determine if variable is undefined or null?).

If you need to remove keys at various nested levels in your object or in an object where some of the nested values are of different types, then check out some of the other answers that employ recursion and type checking.

For example:

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

Object.values(req).forEach(v => {
  Object.keys(v).forEach(k => {
    if (v[k] == null) {
      delete v[k];
    }
  });
});

console.log(req);
// {"adtForm1":{"firstName":"John","middleName":""},"adtForm2":{"lastName":"Doe","middleName":""}}
Answer:3

If I understand, you need to modify the actual object instead of creating a new structure. If so, then you don't want .reduce(). You just need a recursive function that modifies the given object.

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

function removeUndefinedFormsAttributes(obj) {
  Object.entries(obj)
    .forEach(([k, v]) => {
      if (v == null) {
        delete obj[k];
      } else if (typeof v === "object") {
        removeUndefinedFormsAttributes(v);
      }
    })
};

removeUndefinedFormsAttributes(req);

console.log(req);
Answer:4

Try this one

  let removeNotNeedet = ( obj ) => {
    let newObj = {} 
    for (const key in obj) {
        if ( obj[key] !== null && obj[key] !== undefined ){
            newObj[key] = obj[key]
        }
    }
    return newObj
  }
Answer:5

In my scenario <MainComponent /> having so many subcomponents .But particular subcomponent i need to populate the new data with all other subcomponents. var MainComponent = React.createClass({ ...

In my scenario <MainComponent /> having so many subcomponents .But particular subcomponent i need to populate the new data with all other subcomponents. var MainComponent = React.createClass({ ...

I guess we can say that this is very similar to an already asked question here (Optimisation/knapsack algorithm with multiple contraints in JavaScript), which hasn't yet an answer. Let say we like ...

I guess we can say that this is very similar to an already asked question here (Optimisation/knapsack algorithm with multiple contraints in JavaScript), which hasn't yet an answer. Let say we like ...

  1. best combination algorithm
  2. find best combination algorithm

Premise Let's say I have two different AMD-based AngularJS apps, each of them with their own sets of controllers, directives, services, etc. Each of them are bundled in their own dist/{app-name}.min....

Premise Let's say I have two different AMD-based AngularJS apps, each of them with their own sets of controllers, directives, services, etc. Each of them are bundled in their own dist/{app-name}.min....

  1. do containers share common dependencies

So, I have a page, where when a user holds left mouse button, Shrek images are drawn where his/her cursor is. The problem is, only one picture is created when the mouse is down, but I need an ENDLESS ...

So, I have a page, where when a user holds left mouse button, Shrek images are drawn where his/her cursor is. The problem is, only one picture is created when the mouse is down, but I need an ENDLESS ...