I have the following sample JSON object:
var data = [ {
"id" : 1,
"name" : "Abc",
"age" : 30,
"married" : true,
"city": "ABC"
}, {
"id" : 2,
"name" : "Def",
"age" : 25,
"married" : true,
"city": "ABC"
}, {
"id" : 3,
"name" : "Pqr",
"age" : 28,
"married" : false,
"city": "ABC"
}, {
"id" : 4,
"name" : "Xyz",
"age" : 40,
"married" : true,
"city": "ABC"
} ];
I want to return true
and store it in a variable if all city
key values are ABC
only, or else it should return false
(i.e if one of city
key values is not ABC
) from the given JSON
object. Can anyone please let me know on how to achieve this. Thanks in advance.
Using Array#every
:
const data = [ { "id" : 1, "name" : "Abc", "age" : 30, "married" : true, "city": "ABC" }, { "id" : 2, "name" : "Def", "age" : 25, "married" : true, "city": "ABC" }, { "id" : 3, "name" : "Pqr", "age" : 28, "married" : false, "city": "ABC" }, { "id" : 4, "name" : "Xyz", "age" : 40, "married" : true, "city": "ABC" } ];
const valid = data.every(({ city }) => city === 'ABC');
console.log(valid);