问题描述
我有一个具有多个属性的对象。我想删除任何有假值的属性。
I have an object with several properties. I would like to remove any properties that have falsy values.
这可以通过,但对象呢?
This can be achieved with compact
on arrays, but what about objects?
推荐答案
你可以制作自己的下划线插件(mixin):
You could make your own underscore plugin (mixin) :
_.mixin({
compactObject: function(o) {
_.each(o, function(v, k) {
if(!v) {
delete o[k];
}
});
return o;
}
});
然后将其用作本机下划线方法:
And then use it as a native underscore method :
var o = _.compactObject({
foo: 'bar',
a: 0,
b: false,
c: '',
d: null,
e: undefined
});
更新
因为 ,这个mixin影响原始对象,而原始 compact
下划线方法。
解决此问题并使我们的 compactObject
表现得更像是 cousin ,这是一个小小的更新:
Update
As @AndreiNeculau pointed out, this mixin affects the original object, while the original compact
underscore method returns a copy of the array.
To solve this issue and make our compactObject
behave more like it's cousin, here's a minor update:
_.mixin({
compactObject : function(o) {
var clone = _.clone(o);
_.each(clone, function(v, k) {
if(!v) {
delete clone[k];
}
});
return clone;
}
});
这篇关于使用Underscore.js从Object中删除空属性/ falsy值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!