Best way to take out keys with invalid (NaN, blank, etc) values from an object?

微笑、不失礼 提交于 2019-12-06 14:05:30

With underscore 1.7.0+, you can easily filter the query object with _.pick():

searchParams = _.pick(searchParams, function(val) { 
  return !!val;
});

... that'll create an object with only those properties that were assigned truthy values.

You can do the same thing, but in a slightly different way, with _.omit():

searchParams = _.omit(searchParams, function(val) { 
  return !val;
});

In this case, all the properties with falsy values will be dropped.


For the completeness sake, here's a vanilla JS way:

var filteredSearchParams = {};
for (var prop in searchParams) {
  if (searchParams.hasOwnProperty(prop) && !!searchParams[prop]) {
    filteredSearchParams[prop] = searchParams[prop];
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!