I encountered an issue when attempting to remove keys from a JSON object:
var data = this.data;
Object.keys(data).forEach(function(key) {
if (isEmptyProperty(data[key])){
delete data[key];
};
});
The loop above iterates through a JSON object with the following structure:
{ notes: [],
isHostessGift: false,
playbook: {},
location: {},
wine: { ingredient: false, pairing: false },
coupons: [],
ingredients: [{ item: 'e' }],
categories: { dishType: ["Beverage"], mainIngredient: ["e"] },
directions: [{ step: 'e' }],
headline: 'jnj' }
It aims to eliminate keys with empty arrays like 'coupons' and 'notes'
However, it's not working as intended. Interestingly, when I manually added quotes around the keys in the data:
{ "notes": [],
isHostessGift: false,
playbook: {},
location: {},
wine: { ingredient: false, pairing: false },
"coupons": [],
ingredients: [{ item: 'e' }],
categories: { dishType: ["Beverage"], mainIngredient: ["e"] },
directions: [{ step: 'e' }],
headline: 'jnj' }
The keys were successfully removed. What could be causing this difference in behavior?
function isEmptyProperty(obj) {
for (var key in obj) {
if (hasOwnProperty.call(obj, key)){
if(typeof obj === 'function') return false;
if (obj == null) return true;
if (obj.length === 0) return true;
if(_.isEmpty(obj)) return true;
if (obj.length > 0) return false;
};
return false;
}
}