Javascript 使用 Underscore.js 从对象中删除空属性/虚假值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14058193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove empty properties / falsy values from Object with Underscore.js
提问by Emil Lundberg
采纳答案by gion_13
You could make your own underscore plugin (mixin) :
您可以制作自己的下划线插件(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
});
Update
更新
As @AndreiNeculaupointed out, this mixin affects the original object, while the original compactunderscore method returns a copy of the array.
To solve this issue and make our compactObjectbehave more like it's cousin, here's a minor update:
正如@AndreiNeculau指出的那样,这个mixin 影响原始对象,而原始compact下划线方法返回数组的副本。
为了解决这个问题并使我们的compactObject行为更像它的堂兄,这里有一个小更新:
_.mixin({
compactObject : function(o) {
var clone = _.clone(o);
_.each(clone, function(v, k) {
if(!v) {
delete clone[k];
}
});
return clone;
}
});
回答by Emil Lundberg
Since Underscore version 1.7.0, you can use _.pick:
从 Underscore 版本 1.7.0 开始,您可以使用_.pick:
_.pick(sourceObj, _.identity)
Explanation
解释
The second parameter to _.pickcan be a predicate function for selecting values. Values for which the predicate returns truthyare picked, and values for which the predicate returns falsyare ignored.
第二个参数 to_.pick可以是用于选择值的谓词函数。选择谓词返回真值的值,忽略谓词返回假的值。
pick_.pick(object, *keys)
Return a copy of the object, filtered to only have values for the whitelisted keys(or array of valid keys). Alternatively accepts a predicate indicating which keys to pick.
选择_.pick(object, *keys)
返回object的副本,过滤后仅包含白名单键(或有效键数组)的值。或者接受一个指示选择哪些键的谓词。
_.identityis a helper function that returns its first argument, which means it also works as a predicate function that selects truthy values and rejects falsy ones. The Underscore library also comes with a bunch of other predicates, for instance _.pick(sourceObj, _.isBoolean)would retain only boolean properties.
_.identity是一个返回其第一个参数的辅助函数,这意味着它也可以用作选择真值并拒绝假值的谓词函数。Underscore 库还带有一堆其他谓词,例如_.pick(sourceObj, _.isBoolean)只保留布尔属性。
If you use this technique a lot, you might want to make it a bit more expressive:
如果你经常使用这种技术,你可能想让它更具表现力:
var pickNonfalsy = _.partial(_.pick, _, _.identity); // Place this in a library module or something
pickNonfalsy(sourceObj);
Underscore version 1.6.0 provided _.pickas well, but it didn't accept a predicate function instead of a whitelist.
也提供了 Underscore 版本 1.6.0 _.pick,但它不接受谓词函数而不是白名单。
回答by Shwaydogg
Quick 'n Clear: _.omitBy( source, i => !i );
快速清除: _.omitBy( source, i => !i );
This is stated in an inverse fashion to Emil's answer. This way imho reads clearer; it's more self explanatory.
这与埃米尔的回答相反。这样恕我直言,读起来更清晰;它更不言自明。
Slightly less clean if you don't have the luxury of ES6: _.omitBy( source, function(i){return !i;});
如果你没有 ES6 的奢侈,那么干净一点: _.omitBy( source, function(i){return !i;});
Alternate: _.omitBy( source, _.isEmpty)
备用: _.omitBy( source, _.isEmpty)
Using _.isEmpty, instead of _.identityfor truthiness, will also conveniently remove empty arrays and objects from the collection and perhaps inconveniently remove numbers and dates. Thus the outcome is NOT an exact answer to the OP's question, however it could be useful when looking to remove empty collections.
使用_.isEmpty,而不是_.identity为了真实性,还可以方便地从集合中删除空数组和对象,并且可能不方便地删除数字和日期。因此,结果不是 OP 问题的确切答案,但是在删除空集合时它可能很有用。
回答by raine
回答by Florian Margaine
Object.keys(o).forEach(function(k) {
if (!o[k]) {
delete o[k];
}
});
回答by webwise
You can create a shallow clone:
您可以创建一个浅克隆:
_(obj).reduce(function(a,v,k){
if(v){ a[k]=v; }
return a;
},{});
回答by Anoop
for object use delete.
对于对象使用删除。
for(var k in obj){
if(obj.hasOwnProperty(k) && !obj[k]){
delete obj[k];
}
}
回答by Marco Godínez
Suddenly I needed create a function to remove recursively falsies. I hope this helps. I'm using Lodash.
突然间我需要创建一个函数来删除递归错误。我希望这有帮助。我正在使用 Lodash。
var removeFalsies = function (obj) {
return _.transform(obj, function (o, v, k) {
if (v && typeof v === 'object') {
o[k] = _.removeFalsies(v);
} else if (v) {
o[k] = v;
}
});
};
_.mixin({ 'removeFalsies': removeFalsies });
Then you can use it:
然后你可以使用它:
var o = _.removeFalsies({
foo: 'bar',
a: 0,
b: false,
c: '',
d: null,
e: undefined,
obj: {
foo: 'bar',
a: 0,
b: false,
c: '',
d: null,
e: undefined
}
});
// {
// foo: 'bar',
// obj: {
// foo: 'bar'
// }
// }
回答by Geoff Lee
To add to gion_13's answer:
添加到 gion_13 的答案:
_.mixin({
compactObject : function(o) {
var newObject = {};
_.each(o, function(v, k) {
if(v !== null && v !== undefined) {
newObject[k] = v
}
});
return newObject;
}
});
This one creates a new object and adds keys and values instead of cloning everything and deleting key-value pairs. Minor difference.
这个创建一个新对象并添加键和值,而不是克隆所有内容并删除键值对。细微差别。
But more importantly, checks explicitly for null and undefined instead of falsey, which will delete key-value pairs that have false as a value.
但更重要的是,显式检查 null 和 undefined 而不是 falsey,这将删除以 false 作为值的键值对。
回答by Hossein Rezaei
in the lodash you do like this:
在 lodash 你这样做:
_.pickBy(object,?_.identity);

