如何从多深度JavaScript对象中删除空属性? [英] How to remove Empty Properties from a multi depth JavaScript Object?

查看:65
本文介绍了如何从多深度JavaScript对象中删除空属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个JS对象:

var test = {"code_operateur":[""],"cp_cult":["",""],"annee":["2011"],"ca_cult":[""]}

当我使用此功能时:

for (i in test) {  
   if ( test[i] == "" || test[i] === null ) {  
       delete test[i];  
    }  
}

我得到:

{"cp_cult":["",""],"annee":["2011"]}

好的不错,但我想删除空的cp_cult属性(这是一个数组,而不是像另一个那样的字符串)。

Okay not bad, but I'd like to remove the empty "cp_cult" property (which is an array and not a string like the other).

注意:我不想手动删除密钥!

Note: I don't want to manually delete the key!

推荐答案

尝试:

function isEmpty(thingy) {
 for(var k in thingy){
  if(thingy[k]) {
   return false;
  }
 }
 return true;
}

for(i in test) {
 if ( test[i] == "" || test[i] === null || (typeof test[i] == "object" && isEmpty(test[i])) ) {
  delete test[i];
 }
}

但是,根据对象的复杂程度,你需要更高级的算法。例如,如果数组可以包含另一个空字符串数组(甚至更多级别)并且应该删除它,那么您也需要检查它。

However, depending on the complexity of the object, you'd need more advanced algorithms. For example, if the array can contain another array of empty strings (or even more levels) and it should be deleted, you'd need to check for that as well.

编辑:请尝试制作符合您需求的产品,请查看: http:/ /jsfiddle.net/jVHNe/

Trying to make something to fit your needs, please have a look at: http://jsfiddle.net/jVHNe/

这篇关于如何从多深度JavaScript对象中删除空属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆