byrdr
byrdr

Reputation: 5487

javascript can't delete object key when not in quotes

I've come across an issue while trying to remove keys from a json object:

var doc = this.data;
  Object.keys(doc).forEach(function(key) {
      if (isPropertyEmpty(doc[key])){
        delete doc[key];
      };
  }); 

The following loop passes over a JSON object which is formatted like this:

{ 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 should remove the keys with empty arrays: coupons and notes

For some reason it isn't, but when I hard-coded the data, adding quotes around the keys:

{ "notes": [],
isHostessGift: false,
  playbook: {},
  location: {},
  wine: { ingredient: false, pairing: false },
  "coupons": [],
  ingredients: [{ item: 'e' }],
  categories: { dishType: ["Beverage"], mainIngredient: ["e"] },
  directions: [{ step: 'e' }],
  headline: 'jnj' }

They are removed. Is there any reason for the difference in functionality?

function isPropertyEmpty(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;
}


 }

Upvotes: 0

Views: 149

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77482

As I said before problem in isPropertyEmpty, for empty arrays it returns undefined, I've rewritten it and seems works fine

var doc = { 
    "notes": [],
	isHostessGift: false,
    playbook: {},
    location: {},
    wine: { ingredient: false, pairing: false },
    "coupons": [],
    ingredients: [{ item: 'e' }],
    categories: { dishType: ["Beverage"], mainIngredient: ["e"] },
    directions: [{ step: 'e' }],
    headline: 'jnj'
};

Object.keys(doc).forEach(function(key) {
    if (isPropertyEmpty(doc[key])) {
        delete doc[key];
    };
});


function isPropertyEmpty(obj) {
    var hasOwnProperty = Object.prototype.hasOwnProperty;

    if (obj === null || obj.length === 0) {
        return true;
    }
    
    if (typeof obj === 'function' || typeof obj === 'boolean') {
        return false;
    }

    if (obj.length > 0) {
        return false;
    }
    
    for (var key in obj) {
        if (hasOwnProperty.call(obj, key)) {
            return false;
        }
    }

    return true;
}


console.log(doc);

Upvotes: 2

Related Questions