[英]How to check and return true if json object key is having all same values in javascript?
I have the following sample JSON object:我有以下示例 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
(ie if one of city
key values is not ABC
) from the given JSON
object.如果所有
city
键值仅是ABC
,我想返回true
并将其存储在变量中,否则它应该从给定的JSON
object 返回false
(即,如果city
键值之一不是ABC
)。 Can anyone please let me know on how to achieve this.谁能告诉我如何实现这一目标。 Thanks in advance.
提前致谢。
Using Array#every
:使用
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);
Three possible ways of achieving this:实现这一目标的三种可能方法:
Array#every
Array#every
Array#some
Array#some
Array#filter
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);
simply:简单地:
data.filter(x => x.city === 'ABC')
Please do a more detailed search about the problem before opening a topic.请在打开主题之前对问题进行更详细的搜索。
data.some((el) => el.city !== "ABC")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.