Home > Software engineering >  delete from json conditionally
delete from json conditionally

Time:02-08

I have some JSON that looks like this

var js = '{
            "person" : {
                        "firstname" : "Steve",
                        "lastname" : "Smith",
                        "other": [
                                    { 
                                       "age" : "32",
                                       "deceased" : false
                                    },
                                    { 
                                       "age" : "14",
                                       "deceased" : false
                                    },
                                    { 
                                       "age" : "421",
                                       "deceased" : false
                                    }
                                 ]
                       }
         }'

I know how I delete all of "other" by doing this

var j = JSON.parse(js)
delete j[person.other]

but what I really want is to delete the "other" node with a condition that is age = 14.

The result JSON I am looking for is

{
            "person" : {
                        "firstname" : "Steve",
                        "lastname" : "Smith",
                        "other": [
                                    { 
                                       "age" : "32",
                                       "deceased" : false
                                    },
                                    { 
                                       "age" : "421",
                                       "deceased" : false
                                    }
                                 ]
                       }
}

I have looked at the delete operator here and it does not provide a conditional.

Sorry if this is too simple a question. I am learning.

Thanks

CodePudding user response:

You can use a filter on the array doing something like

j[person.other].filter(x => x.age != 14)

Doc on how filter works more in depth here :

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

CodePudding user response:

The best approach to this would be not to alter the json, but create another one instead:

const filtered = { ...json, other: json.other.filter(item => item.age !== "14") }

If you really need to alter the json, you can do the following:

let index = json.other.findIndex(item => item.age === "14")
while (index !== -1) {
  json.other.splice(index, 1)
  index = json.other.findIndex(item => item.age === "14")
}
  •  Tags:  
  • Related