I have a requirement where in I need to remove the objects which do not have certain property and delete it from an array of objects in javascript.Below is the input.
var array=[
{
"id": "1",
"name": "john",
"grade": "grade 1"
},
{
"id": "4",
"name": "sam",
"grade": "grade 1",
"DOB": null,
"marks": 73,
"result":"PASS"
},
{
"id": "3",
"name": "peter",
"grade": "grade 1"
},
{
"id": "5",
"name": "robin",
"grade": "grade 1",
"marks": 63,
},
{
"id": "2",
"name": "james",
"grade": "grade 1",
"DOB": null,
"result":"PASS"
}
]
requirement is to remove objects which do not have marks or dob or result field. I tried the following code and it throws error at delete step
const filteredArray = array.filter( item => {
if(!(('DOB' in item)||('marks' in item)||('result' in item))){
console.log("ITEM DOESN'T HAVE FIELDS___DELETING IT")
delete item
}
})
The expected output is as follows
[
{
"id": "4",
"name": "sam",
"grade": "grade 1",
"DOB": null,
"marks": 73,
"result":"PASS"
},
{
"id": "5",
"name": "robin",
"grade": "grade 1",
"marks": 63,
},
{
"id": "2",
"name": "james",
"grade": "grade 1",
"DOB": null,
"result":"PASS"
}
]
How do I achieve it?
3
Answers
The callback function must return a value whose truth value indicates whether the element should be included in the result. It doesn’t delete elements by itself.
Try the following:
Simplest version