【问题标题】:Extract from an array of objects ones that have propertie using lodash使用 lodash 从具有属性的对象数组中提取
【发布时间】:2018-01-04 10:57:54
【问题描述】:

我有一大堆对象,我需要获取具有def 属性集的对象。没有mather价值... 提前致谢。

【问题讨论】:

标签: javascript arrays object lodash


【解决方案1】:

您可以使用hasOwnProperty 检查是否存在属性,使用Array.prototype.filter 仅过滤这些项目。

objArray = [ { def: 1, bar: 2}, { foo: 3, bar: 4}, { def: 5, bar: 6} ];

var result = objArray.filter(item => item.hasOwnProperty('def'));
console.log(result);

为了 es5 兼容性

objArray = [{
  def: 1,
  bar: 2
}, {
  foo: 3,
  bar: 4
}, {
  def: 5,
  bar: 6
}];

var result = objArray.filter(function(item) {
  return item.hasOwnProperty('def')
});
console.log(result);

【讨论】:

  • @Archer 上面哪个函数对IE有问题?是你指的胖箭头函数吗?
【解决方案2】:

lodash中没有这个功能,你可以试试下面的代码

`let aFilteredArray = [];
    _.forEach(YourArray,function(oElement){
      if(!_.isEmpty(oElement.def)){
        aFilteredArray.push(oElement);
      }
    };

【讨论】:

    猜你喜欢
    • 2015-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多