我有一组像这样的对象:
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的初学者,我想要变得更好。
这是我用过的.dropWhile:
var a2 = _.dropWhile(a, function(o) { return o.CompletedDate == null; });
答案 0 :(得分:5)
您可以使用原生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);
答案 1 :(得分:1)
不需要lodash只过滤
var res = a.filter(x => x.CompletedDate !== null);
答案 2 :(得分:0)
您可以使用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)