1

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

  • 1
    are you looking to filter the array https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter – cmgchess Jun 29 '22 at 10:30

1 Answers1

0

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)
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46