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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With