I have a JSON object: var myObj = {'test':'' , 'test2': '1'}
I want a method on moving over the JSON object and removing all properties that have the empty value ''.
The result:
myObj = {'test2': '1'}
This could be a possible solution:
var jsonObj = '{"test1":"","test2":"2","test3":"","test4":"4"}';
var jsObj = JSON.parse(jsonObj);
function removeNull(element,index,array){
if (this[element] == ""){
delete this[element];
}
}
(Object.getOwnPropertyNames(jsObj)).forEach(removeNull,jsObj);
Check this link jsfiddle to see a working example.
To check whether the properties have been deleted or not:
alert(Object.getOwnPropertyNames(jsObj));
Hope it's useful!
This function do what u want.
var r = function(object){
var _return = {};
for ( var index in object ){
if(object[index] != ''){
_return[index] = object[index];
}
}
return _return ;
};
Try this jsfiddle !
Code:
var myObj = {'test':'' , 'test2': '1','test3': '2'}
var obj = myObj;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
delete obj[key];
console.log(val);
}
}
for (var key in obj) {
var val = obj[key];
alert(val);
//console.log(val);
}
If you want more info about understanding delete check this blog.