如何从多深度 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”属性(它是一个数组,而不是像另一个一样的字符串)。
注意:我不想手动删除密钥!
I've got this JS Object:
var test = {"code_operateur":[""],"cp_cult":["",""],"annee":["2011"],"ca_cult":[""]}
When I use this function:
for (i in test) {
if ( test[i] == "" || test[i] === null ) {
delete test[i];
}
}
I get:
{"cp_cult":["",""],"annee":["2011"]}
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来你在这里问了 2 个问题。
您可以使用
delete
运算符删除对象的属性。在 JavaScript 中,数组是对象,这意味着
typeof([])
无济于事地返回object
。通常,人们通过使用框架中的函数(dojo.isArray 或类似的东西)或滚动自己的方法来确定对象是否为数组来解决此问题。没有 100% 保证的方法可以确定对象是否实际上是数组。大多数人只是检查它是否具有数组的一些方法/属性
length
、push
、pop
、shift< /code>、
unshift
等。It looks like you're asking 2 questions here.
You can delete a property of an object using the
delete
operator.In JavaScript arrays are objects, which means that
typeof([])
unhelpfully returnsobject
. Typically people work around this by using a function in a framework (dojo.isArray
or something similar) or rolling their own method that determines if an object is an array.There is no 100% guaranteed way to determine if an object is actually an array. Most people just check to see if it has some of the methods/properties of an array
length
,push
,pop
,shift
,unshift
, etc.尝试:
但是,根据对象的复杂性,您需要更高级的算法。例如,如果数组可以包含另一个空字符串数组(甚至更多级别)并且应该将其删除,那么您也需要检查这一点。
编辑:尝试制作一些东西来满足您的需求,请查看:http:// jsfiddle.net/jVHNe/
Try:
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.
EDIT: Trying to make something to fit your needs, please have a look at: http://jsfiddle.net/jVHNe/