[
{
"lastName": "Seymour",
"gender": "Female",
"patientID": 18134,
"firstName": "Stephanie",
"age": "111Y"
},
{
"lastName": "Seymour",
"gender": "Female",
"patientID": 18134,
"firstName": "Stephanie",
"age": "111Y"
}
]
How can i check my json before adding whether it contains this value or not...
what is "contains this value"? do you mean, the two items have all the fields equal?
in this case you may serialize to string (json) each item and compare the new one (serialized also) to the set of existing.
Obvious way
The most obvious way would be to use a
for
loop and iterate over all items in array and compare every time when you'd like to know whether you already have a particular item in it. Trivial but tedious especially when you have many compares to make.Whenever you'd be searching for existing object:
Smart(er) way
This code uses the ability of Javascript whose prototypes can be used as arrays in a sort of associative memory storage. Suppose you have your JSON items in
arr
variable. Define your compare key (say it's first name and last name):Finding out whether you already have an item in your array is then pretty simple:
And that's it. Much faster than iterating over the whole array. Especially when it has many items.