0

I have a ajax request which returns data in json format like

{
    "response_code": 1,
    "response_data": {
        "ext": [
            {
                "client_id":"1003",
                "company_name":"Reachmediagg"
            },
            {
                "client_id":"1004",
                "company_name":"RaSpecial"
            }
        ],
        "row_count":2
    },
    "response_error":""
}

As you can see the data is inside the ext array inside json object, now I have to get the row number of the data, so I want for example row number of client_id 1004, which is 2. How will I do that in javascript?

StoicJester
  • 364
  • 2
  • 12
Garima Jain
  • 11
  • 1
  • 2

2 Answers2

2

You have to loop through the ext array in your JSON and find the element that holds the correct client_id. The function described below does just that.

function get_row_number(data, client_id) {
    var ext = data.ext;

    // Loop through all the clients and try to find the one with the given client_id
    for (var i = 0; i < ext.length; i++) {
        if (ext[i].client_id == client_id)
            return i;
    }

    // Return -1 if the client_id could not be found
    return -1;
}
Thijs Riezebeek
  • 1,762
  • 1
  • 15
  • 22
0

Technically the data doesn't have row numbers. Only in how you read the data can you infer/assign a row number.

Note that ext is an array. You can loop over that array until you find the record you want and keep a counter. For example:

var counter = 0;
for (;counter <= response_data.ext.length; counter++) {
    if (response_data.ext[counter].client_id == 1004) {
        break;
    }
}
// here "counter" is the "row number" where client_id == 1004

You can also extract this into a function where the target client_id is a parameter (or the condition itself is a parameter, allowing you to look for more than just client_id).

David
  • 208,112
  • 36
  • 198
  • 279