Steve
Steve

Reputation: 89

delete from json conditionally

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

Upvotes: 0

Views: 1632

Answers (2)

Tiago Peres França
Tiago Peres França

Reputation: 3215

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")
}

Upvotes: 1

cdelaby
cdelaby

Reputation: 11

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

Upvotes: 1

Related Questions