3

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?

mnsr
  • 12,337
  • 4
  • 53
  • 79
Birish
  • 5,514
  • 5
  • 32
  • 51
  • 1
    This really has nothing to do with react. But if you're using a library like lodash, you can do `const loc = locations.filter(i => i.id === XXXX)` – mnsr Jul 21 '16 at 04:48
  • I would recommend to start with the following answer: http://stackoverflow.com/a/11922384/133645 – reto Jul 21 '16 at 04:51
  • Why do you need a library to be able to filter? – Evan Trimboli Jul 21 '16 at 04:54
  • @EvanTrimboli You don't. I forgot to delete that part and now i can't edit the comment. The example i wrote isn't using lodash, it's using the standard Array.filter – mnsr Jul 21 '16 at 05:03

2 Answers2

0

you can use underscorejs

let array_of_ids = _.pluck(json_object.locations,"id")

//now find the index of your particular id

let index = _.indexOf(array_of_ids,yourId)

//now your required object is

let your_object = json_object.locations[index]

Thats it

cheers

khem poudel
  • 587
  • 7
  • 13
0

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>
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400