Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve JSON Array element in ReactJS

Tags:

json

I have the following json file in ReactJS:

{
  "locations": [
      {
        "id": 8817,
        "loc": "NEW YORK CITY"
      },
      {
        "id": 2873,
        "loc": "UNITED STATES"
      },
      {
        "id": 1501
        "loc": "NEW YORK STATE"
      }
    ]
}

How can I get the value of a an element where the id=xxxx? Also how can I get the loc when id=xxxx?

like image 676
Birish Avatar asked Oct 20 '25 13:10

Birish


1 Answers

You can use the filter function.

var obj = {
  "locations": [
      {
        "id": 8817,
        "loc": "NEW YORK CITY"
      },
      {
        "id": 2873,
        "loc": "UNITED STATES"
      },
      {
        "id": 1501,
        "loc": "NEW YORK STATE"
      }
    ]
}
var val = '8817';
var res = obj.locations.filter(function(item) {
    return item.id == val;
  });

  console.log(res[0].loc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
like image 149
Shubham Khatri Avatar answered Oct 23 '25 03:10

Shubham Khatri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!