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
- it first check empty age.
- if empty age, send false alert. if sends false alert, item not in
final
. - else try check duplicate
alias
. if item exists in temp list that's mean it's passed once. returnfalse
. - if no item exists in temp list, push item in temp , return
true
. - if total item in
final
not same equaldata
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")
Comments
Post a Comment