Reputation: 9299
what is the recommended way to query json data? for example my data looks like
var meetings =
{
"meeting" : [
{
"subject" : "Server upgrade for data center C3W",
"attendees" : [
{
"name" : "Ron Edward",
"title": "CEO",
"company": "Data Solutions",
"confirmed" : "yes"
},
{
"name" : "John Steward",
"title": "Procurement Officer",
"company": "Data Solutions",
"confirmed" : "yes"
},
{
"name" : "Name 1",
"title": "Senior Director",
"company": "C1 Corporation",
"confirmed" : "no"
}
]
}
]
}
;
and i want to query like if there is any of the attendee with confirmed no value
Upvotes: 1
Views: 346
Reputation: 2742
Your question is not clear about whether you want to check if there exists any attendee who has not confirmed , or you want to find which attendees have not confirmed ? In both cases the code is almost the same with a minor difference :-
Common Code
function checkConfirmation(person){
return person.confirmed == "no"
}
Explantion : This function returns true if the if an object with property confirmed is set to no
Case I : If you only want to find whether there is a person who has not confirmed yet
var result = meetings["meeting"][0]["attendees"].some(checkConfirmation);
console.log(result); // true
Explantion : The "some()" is a Javascript Array Method which checks whether any of the member of the array fullfill the condition of the function and return Boolean . In your case it will be true as one attendee has not confirmed yet.
Case II : If you only want to find which all persons have not confirmed .
var result = meetings["meeting"][0]["attendees"].filter(checkConfirmation);
console.log(result); // [ { name: 'Name 1',title: 'Senior Director', company: 'C1 Corporation', confirmed: 'no' } ]
Explantion : The "filter()" is a Javascript Array Method which returns another array{a subarray of the original}, the members which fullfill the condition of the function . In your case it will have one member .
A little more about these methods :- https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
Upvotes: 2