Reputation: 740
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
Upvotes: 1
Views: 1036
Reputation: 7325
function getCleanObject(oldObject) {
var newObject = {};
for (var property in oldObject) {
var value = oldObject[property];
if (value) newObject[property] = value;
}
}
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
(i.e. list). Also in
is supported in all browsers whereas of
is not supported by internet explorer
.
Upvotes: 4
Reputation: 752
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
Upvotes: 0