Reputation: 138
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.
Upvotes: 1
Views: 2058
Reputation: 8168
Three possible ways of achieving this:
Array#every
Array#some
Array#filter
let data = [{id:1,name:"Abc",age:30,married:!0,city:"ABC"},{id:2,name:"Def",age:25,married:!0,city:"ABC"},{id:3,name:"Pqr",age:28,married:!1,city:"ABC"},{id:4,name:"Xyz",age:40,married:!0,city:"ABC"}];
console.log(data.every(({ city }) => city === "ABC"));
console.log(!data.some(({ city }) => city !== "ABC"));
console.log(!data.filter(({ city }) => city !== "ABC").length);
Upvotes: 2
Reputation: 555
simply :
data.filter(x => x.city === 'ABC')
Please do a more detailed search about the problem before opening a topic.
Upvotes: 1
Reputation: 28414
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);
Upvotes: 3