A
A
Alexey2014-12-04 15:23:34
JavaScript
Alexey, 2014-12-04 15:23:34

How to get the index of an object in JSON by its id?

The situation is this, I have a json file with the following structure:

[
    {
        ....
        "id": 1,
       ...
    },
    {
        ....
        "id": 2,
       ...
    },
     ...
]


I have an id, for example:
var id = 2;

I need to get the index of the object by this identifier, i.e.
If id = 2, then the index will be:
data[1]

How is it correct to iterate over and return the required index?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
aen, 2014-12-04
@azovl

function getIndexById(arr, id) {
  var index = -1, length = arr.length, i = 0;  
  for (; i < length; i++) {
    if (arr[i]['id'] === id)  {
        index = i;
        break;
    }    
  }
  return index;
}

D
Deodatuss, 2014-12-04
@Deodatuss

like this? jsfiddle.net/a5qpp8ry

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question