如何从属性等于Null的数组中删除对象- Lodash

How to Remove Object From Array Where Property Equals Null - Lodash

本文关键字:删除 对象 Lodash 数组 从属性 Null      更新时间:2023-09-26

我有一个像这样的对象数组:

var a = [
  {
    "ClientSideAction": 1,
    "CompletedDate": "not null",
    "ItemDescription": "Step 1"
  },
  {
    "ClientSideAction": 1,
    "CompletedDate": null,
    "ItemDescription": "step 2"
  },
  {
    "ClientSideAction": 1,
    "CompletedDate": "not null",
    "ItemDescription": "Step 3"
  },
  {
    "ClientSideAction": 1,
    "CompletedDate": null,
    "ItemDescription": "step 4"
  }
];

如何删除CompletedDate == null所在的元素?

我试过._dropWhile,但它停止一旦函数返回假的,这不是我想要的。我想循环遍历所有对象并删除那些符合条件的对象。现在,我知道我可以使用常规js,但我想使用lodash,如果可能的话。我是Lodash的初学者,我正在努力做得更好。

这是我使用的。dropwhile:

var a2 = _.dropWhile(a, function(o) { return o.CompletedDate == null; });

您可以使用本机Array.filter()进行过滤。

var a = [
  {
    "ClientSideAction": 1,
    "CompletedDate": "not null",
    "ItemDescription": "Step 1"
  },
  {
    "ClientSideAction": 1,
    "CompletedDate": null,
    "ItemDescription": "step 4"
  }
];
var b = a.filter(function(item) {
  return item.CompletedDate !== null;
});
console.log(b);

这可以在现代浏览器或nodejs中使用箭头函数进一步简化:

var b = filter((x => x.CompletedDate !== null);

不需要lodash只是过滤器

var res = a.filter(x => x.CompletedDate !== null);

可以使用Array。过滤器

var a = [
  {
    "ClientSideAction": 1,
    "CompletedDate": "not null",
    "ItemDescription": "Step 1"
  },
  {
    "ClientSideAction": 1,
    "CompletedDate": null,
    "ItemDescription": "step 2"
  },
  {
    "ClientSideAction": 1,
    "CompletedDate": "not null",
    "ItemDescription": "Step 3"
  },
  {
    "ClientSideAction": 1,
    "CompletedDate": null,
    "ItemDescription": "step 4"
  }
];
var a = a.filter(function(v) {
  return v.CompletedDate != null;
})
console.log(a)