user1937021 user1937021 - 2 months ago 13
jQuery Question

Get data from JSON object using value within

My JSON is as follows:

{
"sales": [{
"manager": "alberic",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "USA",
"percent-seller": "30",
"antiquity": "June 2017",
"date": "6"
}, {
"manager": "support",
"surgeon": "Dr Barry Biggins",
"amount": "300",
"country": "UK",
"percent-seller": "20",
"antiquity": "June 2017",
"date": "2"
}, {
...
}]
}


I want to retrieve the objects from
sales
where
manager = "support"
and
date = "2"
. How do I go about this in jQuery?

Thanks!

Answer

Simply you can use filter() method and use your condition inside filter method function will return element if your condition become true otherwise it ignore element.

data=    {"sales": [{
          "manager": "alberic",
          "surgeon": "Dr Barry Biggins",
          "amount": "300",
          "country": "USA",
          "percent-seller": "30",
          "antiquity": "June 2017",
          "date": "6"
        }, {
          "manager": "support",
          "surgeon": "Dr Barry Biggins",
          "amount": "300",
          "country": "UK",
          "percent-seller": "20",
          "antiquity": "June 2017",
          "date": "2"
        },
       ]
      };


var matchedElements = data.sales.filter(function(element) {
   return (element.manager == 'support' && element.date == '2');
});
                   
console.log(matchedElements);
                    
//if you want to access  surgeon of first element of matchedElements
                    
console.log(matchedElements[0].surgeon);

          
//if you want to access  surgeon of all elements in matchedElements
for(i in matchedElements)           
{
console.log(matchedElements[i].surgeon);
}