I have the below response body (json) I want to do the below checks
1) Check if 'id=5' exist
I have the below response body (json) I want to do the below checks
1) Check if 'id=5' exist
You can use some
method to check whether array satisfies some conditions:
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 }`);
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();
Hope this helps :)