不在引号

时间:2015-10-07 15:37:01

标签: javascript json

我在尝试从json对象中删除键时遇到了一个问题:

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

以下循环遍历JSON对象,格式如下:

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

它应该删除空数组的键:优惠券和笔记

出于某种原因它不是,但是当我对数据进行硬编码时,在键周围添加引号:

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

他们被删除了。功能上有什么不同的原因吗?

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;
}


 }

1 个答案:

答案 0 :(得分:2)

正如我之前在isPropertyEmpty中提到的问题所说的那样,对于空数组,它会返回undefined,我已经重写了它并且似乎工作正常



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);