简体   繁体   中英

How to remove undefined property from object?

I have this object:

  this.prepaidObject = {
            'customerType' : this.prepaidDetailForm.prepaidDetails.customerType,
            'firstName' : this.prepaidDetailForm.prepaidDetails.firstName,
            'lastName' : this.prepaidDetailForm.prepaidDetails.lastName,
            'note' : this.prepaidDetailForm.prepaidDetails.note,
            'created': this.prepaidDetailForm.prepaidDetails.created
        };

Now sometimes some of this property are undefined. What i want is if one of this.prepaidDetailForm.prepaidDetails properties are undefined not to display them. So for example if this.prepaidDetailForm.prepaidDetails.firsName is undefined i dont need to create 'firstName' property isnide object. Any suggestion how can i do that?

Check your object:

    for( var m in this.prepaidObject ) {
        if ( this.prepaidObject[m] == undefined ) {
            delete this.prepaidObject[m];
        }
    } 

The shortest way to do this is to parse it after stringify .

The exact syntax:

let prepaidObjectNew = JSON.parse(JSON.stringify(prepaidObject))

Example

Before:

var prepaidObject = {
    'customerType' : 'TestCustType',
    'firstName' : "sample FirstName",
    'lastName' : "sample LastName",
    'note' : undefined
 };

After:

{
    'customerType' : 'TestCustType',
    'firstName' : "sample FirstName",
    'lastName' : "sample LastName"
 };

One way is to go through the keys and only append the defined ones:

this.prepaidObject = { };
Object.keys(this.prepaidDetailForm.prepaidDetails)
     .forEach(function(key) {
           var val = this.prepaidDetailForm.prepaidDetails[key];
           if (val !== undefined) {
                this.prepaidObject[key] = val;
           }
     });

This is assuming the keys in prepaidObject are the same as in prepaidDetails and all of them follow the same rule you mention.

Especially if you're using ES6 you might make this more elegant using map and reduce like so:

this.prepaidObject = Object.keys(this.prepaidDetailForm.prepaidDetails)
     .map(key => ({key, val: this.prepaidDetailForm.prepaidDetails[key]}))
     .reduce((obj, {key, val}) => {
          if (val !== undefined) {
               obj[key] = val;
          }
          return obj;
     }, {});

And an even more succinct approach using more ES6 features:

this.prepaidObject = Object.keys(this.prepaidDetailForm.prepaidDetails)
     .map(key => ({key, val: this.prepaidDetailForm.prepaidDetails[key]}))
     .filter(({_, val}) => val !== undefined)
     .reduce((obj, {key, val}) => Object.assign(obj, { [key]: val }), {});

Using Lodash make it too easy in one line:

_.pickBy(this.prepaidObject, _.identity);

That would remove all falsey values

You probably need to check the type.

(typeof(this.prepaidDetailForm.prepaidDetails.firsName) != "undefined") ? this.prepaidDetailForm.prepaidDetails.firsName : ''

Its basically:

var firstName = '';
if(typeof(this.prepaidDetailForm.prepaidDetails.firsName) != "undefined")
     firstName = this.prepaidDetailForm.prepaidDetails.firsName;

Please try following:

 for (var propName in this.prepaidObject) { 
    if (this.prepaidObject[propName] === undefined) {
      delete this.prepaidObject[propName];
    }
  }

And look at following answers: Remove blank attributes from an Object in Javascript

this.prepaidObject = {};
for (var i in this.prepaidDetailForm.prepaidDetails) {
  if (typeof(this.prepaidDetailForm.prepaidDetails[i]) !== 'undefined') {
    this.prepaidObject[i] = this.prepaidDetailForm.prepaidDetails[i];
  } 
} 

If you want to exclude also null values and undefined, change the condition to:

if (this.prepaidDetailForm.prepaidDetails[i] != null)

Not the double ==. because null == undefined but null !== undefined

Assume you have an object like below one,

var prepaidObject = {
    'customerType' : 'TestCustType',
    'firstName' : "sample FirstName",
    'lastName' : "sample LastName",
    'note' : undefined
 };

You can remove undefined using JSON.parse and JSON.stringify method,

JSON.parse(JSON.stringify(prepaidObject));
console.log(prepaidObject)

Output will be,

{
    'customerType' : 'TestCustType',
    'firstName' : "sample FirstName",
    'lastName' : "sample LastName"
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM