javascript - In Jquery, How to check empty and duplicate value in Json object? -


var data = {   "obj":[{     "name": "john",     "age": "10",     "alias": "person",     "where":[{"city1":"foo", "city2":"foo2"}]   },{     "name": "mike",     "age": "",     "alias": "person",     "where":[{"city1":"test1", "city2":"test2"}]   }] } 

data.obj[0].alias , data.obj[1].alias duplicate.

also data.obj[1].age empty.

if empty or duplicate value exists in json object, return false.

how can check empty , duplicate value?

you can use filter

  1. it first check empty age.
  2. if empty age, send false alert. if sends false alert, item not in final.
  3. else try check duplicate alias. if item exists in temp list that's mean it's passed once. return false.
  4. if no item exists in temp list, push item in temp , return true.
  5. if total item in final not same equal data that's mean there invalid item in in json.

like this

var data = {   "obj": [{     "name": "john",     "age": "10",     "alias": "person",     "where": [{       "city1": "foo",       "city2": "foo2"     }]   }, {     "name": "mike",     "age": "",     "alias": "person",     "where": [{       "city1": "test1",       "city2": "test2"     }]   }] }  var temp = [] var final = data.obj.filter((x, y) => {   console.log(x)   if (x.age.length == 0) {     return false   } else {     if (temp.indexof(x.alias) > -1){       return false     }     else {        temp.push(x.alias)        return true     }   } })  console.log(final.length == data.obj.length ? "valid" : "not valid json") 

demo


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -