【问题标题】:Lodash, taking objects fulfilling requirementsLodash,获取满足要求的对象
【发布时间】:2017-05-17 09:19:20
【问题描述】:

例子:

Animals = [{Name: 'Dog', Id: 0},
           {Name: 'Cat', Id: 1},
           {Name: 'Mouse', Id: null}]

如何将所有 Id 不为空的对象放入新数组中?

预期输出:

NewArray = [{Name: 'Dog', Id: 0},
            {Name: 'Cat', Id: 1}]

【问题讨论】:

  • 你也能说出预期的输出吗
  • 视情况而定,您要更改该数组还是返回一个新数组?
  • 编辑了第一篇文章。

标签: javascript typescript lodash


【解决方案1】:

试试_.filter

var Animals = [{Name: 'Dog', Id: 0},{Name: 'Cat', Id: 1},{Name: 'Mouse', Id:null}]
var newArray =_.filter(Animals ,a=> a.Id != null)
console.log(newArray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.11.2/lodash.min.js"></script>

【讨论】:

  • 或者如果他们想改变当前数组,使用_.remove
  • 以及如何使用 lodash 做到这一点?
  • @ChrisK。使用_.filter。与上面的代码几乎相同。 _.filter(Animals , a=> a.Id != null)
  • @ChrisK。看我更新的答案。我用 lodash 更新了
猜你喜欢
  • 2019-10-06
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 2017-11-27
  • 2019-05-11
  • 2019-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多