简体   繁体   中英

Create JSON object accoring to request.body

Using NodeJs + Express to create a REST API. Everything works well, but I can't understand how to iterate through the request.body and check its fields for undefined and empty values and assign new object only with valid data.

request.body looks like:

{ 
  key: 'value',  
  otherKey: 'otherValue',
  oneMoreKey: '',
  oneMoreKey2: undefined,
  oneMoreKey3: null
}

At that end my object shoud look like:

let contactData = Object.assign({},{
        'key': 'value',
        'otherKey': 'otherValue'
    })

Looking for your advices and help

JavaScript

function getCleanObject(oldObject) {
    var newObject = {};
    for (var property in oldObject) {
        var value = oldObject[property];
        if (value) newObject[property] = value;
    }
}

Explanation

You can start off by creating a new clean Object

var newObject = {}; // same as new Object();

Then iterate through all of the object's properties using a for loop .

for (var property in oldObject)

Then get the value of that property

var value = oldObject[property];

If the value is Troothy add the property to the new Object

 if (value) newObject[property] = value;

Note that this way the false value will be rejected. To allow it to be copied to the new Object you should replace the if statement with

if(value || value === false)

Moreover, if the Object you are copying also inherits from some other Object it is possible that it will have extra properties as well and if you do not want them to be included you should change the if statement to

if(value && oldObject.hasOwnProperty(value))

And Remember for(var item in object) != for(var item of list)

in is used to iterate through an object's properties whereas of is used to iterate through an iteratable (ie list). Also in is supported in all browsers whereas of is not supported by internet explorer .

your_object = {
       key: request.body[key] || 'default',
       otherKey: request.body[otherKey] || 'default',
       oneMoreKey: request.body[oneMoreKey] || 'default'
       ...
}

explanation on how or (||) works JavaScript OR (||) variable assignment explanation

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