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
(i.e. list). Also in
is supported in all browsers whereas of
is not supported by internet explorer
.