[英]How to Remove Object From Array Where Property Equals Null - Lodash
我有一个像这样的对象数组:
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
,但是一旦函数返回falsey,它就会停止,这不是我想要的。 我想遍历所有对象并删除那些符合该条件的对象。 现在,我知道我可以为此使用常规的js,但如果可能的话,我想使用lodash。 我是Lodash的初学者,我正在努力变得更好。
这是我使用的.drop:
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.Filter
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.