Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Splicing JSON object from array

I have tried splicing my json file using a for loop
JSON file:

[
   {
     "name":"Billy Jean",
     "age":"52",
     "sex":"F",
     },
     {
     "name":"Bob Semple",
     "age":"32",
     "sex":"M",
     } there are more....
]

What I have tried (i imported it and called it contactList)

for(let i = 0 ; i < contactList.length ; i++){
   if(contactlist.age > 40) {
         contactList.splice(i, 1);
     }
}

if i run the code and check the output nothing changes in my JSON file

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can create a new array using Array.prototype.filter() combined with Destructuring assignment

  • Notice that age property it’s of type string and should be compared as number using unary plus (+) operator

Code:

const data = [{
    "name": "Billy Jean",
    "age": "52",
    "sex": "F",
  },
  {
    "name": "Bob Semple",
    "age": "32",
    "sex": "M",
  }
]

const result = data.filter(({ age }) => +age > 40)

console.log(result)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading