我具有下面的响应正文(json),我想进行以下检查
1)检查'id = 5'是否存在
答案 0 :(得分:0)
您可以使用some
方法来检查数组是否满足某些条件:
const result = data.some(s=> s.id == 5 && s.name =='John Smith');
const data = [
{
"id": 1,
"name": "George Smith",
"username": "John",
"email": "John@may.biz",
"address": {
"street": "Kennedy",
"suite": "Apt. 332",
"city": "Paris",
"zipcode": "12322-3874",
"geo": {
"lat": "-57.3189",
"lng": "81.1496"
}
},
"phone": "1-999-736-444 x343343",
"website": "web.org",
"company": {
"name": "Amaon",
"catchPhrase": "Multi-layered",
"bs": "e-markets"
}
},
{
"id": 5,
"name": "John Smith",
"username": "johny",
"email": "johny@john.com",
"address": {
"street": "Oxford",
"suite": "Suite 334",
"city": "London",
"zipcode": "12345",
"geo": {
"lat": "-32.3434",
"lng": "45.4543"
}
},
"phone": "(121)954-3457",
"website": "smith.info",
"company": {
"name": "Law LLC",
"catchPhrase": "Customer first",
"bs": "E2E system"
}
}
]
const result = data.some(s=> s.id == 5 && s.name =='John Smith');
console.log(`Has John Smith: ${result}`)
const hasJoseph = data.some(s=> s.id == 5 && s.name =='Joseph');
console.log(`Has Joseph: ${ hasJoseph }`);
答案 1 :(得分:0)
function myFunction() {
var ages = [
{
"id": 1,
"name": "George Smith",
"username": "John",
"email": "John@may.biz",
"address": {
"street": "Kennedy",
"suite": "Apt. 332",
"city": "Paris",
"zipcode": "12322-3874",
"geo": {
"lat": "-57.3189",
"lng": "81.1496"
}
},
"phone": "1-999-736-444 x343343",
"website": "web.org",
"company": {
"name": "Amaon",
"catchPhrase": "Multi-layered",
"bs": "e-markets"
}
},
{
"id": 5,
"name": "John Smith",
"username": "johny",
"email": "johny@john.com",
"address": {
"street": "Oxford",
"suite": "Suite 334",
"city": "London",
"zipcode": "12345",
"geo": {
"lat": "-32.3434",
"lng": "45.4543"
}
},
"phone": "(121)954-3457",
"website": "smith.info",
"company": {
"name": "Law LLC",
"catchPhrase": "Customer first",
"bs": "E2E system"
}
}
];
ages.filter(function(obj) {
return obj.id == 5 && obj.name == 'John Smith';
})
.map(function(obj) {
console.log(obj)
return obj;
});
}
//This method will return the object that matches your condition.
myFunction();
希望这会有所帮助:)