-2

I'm trying to get data out of a JSON using a value.

I have an array of objects:

"fruits": [
    {
        "Name": "Orange",
        "Quantity": "5"
    },
    {
        "Name": "Apple",
        "Quantity": "2"
    }
 ]      

And I also have the name "Apple". How can I get the quantity of Apples?

I'm stuck on this..

Thanks!

dragi
  • 1,462
  • 5
  • 16
  • 28
  • 1
    Are you starting with JSON or do you have a JavaScript object? In either case you are missing the outer braces. – Ray Toal May 16 '19 at 19:05

2 Answers2

3

fruits.find(fruit => fruit.Name==="Apple").Quantity is what you are looking for:

const fruits = [
    {
        "Name": "Orange",
        "Quantity": "5"
    },
    {
        "Name": "Apple",
        "Quantity": "2"
    }
 ]      
 
 console.log(fruits.find(fruit => fruit.Name==="Apple").Quantity);
connexo
  • 53,704
  • 14
  • 91
  • 128
0

Using a forEach you can check each element and if the Name matches get the Quantity

var fruits = [{
    "Name": "Orange",
    "Quantity": "5"
  },
  {
    "Name": "Apple",
    "Quantity": "2"
  }
]

fruits.forEach(function(element) {
  if (element.Name === 'Apple') {
    console.log(element.Quantity)
  }
});
depperm
  • 10,606
  • 4
  • 43
  • 67