我想过滤掉我的具有null
或""
值的对象数组中的对象。
let data = [{
"name": "Product 2",
"link": "/stock/product2",
"category": "234",
"description": ""
}, {
"name": "Product 1",
"link": "/stock/product1",
"category": "1231",
"description": ""
}, {
"name": "",
"link": null,
"ticker": "",
"description": ""
}]
data = data.filter(cv => (cv.name === "" && cv.link === null));
console.log(JSON.stringify(data))
如您在上面所看到的,我目前得到了假对象。我想回来:
{
"name": "Product 2",
"link": "/stock/product2",
"category": "234",
"description": ""
}, {
"name": "Product 1",
"link": "/stock/product1",
"category": "1231",
"description": ""
}
有什么建议我做错了吗?
最佳答案
因为filter
不能按照您的想法工作,所以它会保留满足条件的元素,因此请反转条件,它应能按预期工作:
let data = [{
"name": "Product 2",
"link": "/stock/product2",
"category": "234",
"description": ""
}, {
"name": "Product 1",
"link": "/stock/product1",
"category": "1231",
"description": ""
}, {
"name": "",
"link": null,
"ticker": "",
"description": ""
}]
data = data.filter(cv => !(cv.name === "" || cv.link === null));
console.log(JSON.stringify(data))