Guna
Guna

Reputation: 138

How to check and return true if json object key is having all same values in javascript?

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

Answers (4)

Som Shekhar Mukherjee
Som Shekhar Mukherjee

Reputation: 8168

Three possible ways of achieving this:

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

digitalniweb
digitalniweb

Reputation: 1142

data.some((el) => el.city !== "ABC")

Upvotes: 1

Onur Özkır
Onur Özkır

Reputation: 555

simply :

data.filter(x => x.city === 'ABC')

Please do a more detailed search about the problem before opening a topic.

Upvotes: 1

Majed Badawi
Majed Badawi

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

Related Questions