Kuba ┼╗ukowski Kuba ┼╗ukowski - 1 month ago 7
Javascript Question

JS and JSON - how find number of position

I have JSON file with users_id array. On this array I have active users, so this numbers are not sequential. How I can check (on jQuery) number of position users_id = 18 (answer = 3)? Next I want read value from other string so I can read json.data_todo_counter[3].

{

"users_id": [1, 2, 3, 18, 24],

"data_chat_timeread": [0, 0, 0, 0, 0],
"data_chat_timecurrent": [100, 0, 0, 0, 0],
"data_chat_counter": [4, 0, 0, 0, 0],

"data_todo_counter": [2, 0, 0, 0, 0]

}

Answer

This function searches for the key in the keyMember of input and if found, it returns the element of valueMember at the found index:

function getSomething(input, key, keyMember, valueMember) {
    var index = input[keyMember].indexOf(key);
    if (index >= 0) {
        return input[valueMember][index];
    } else {
        /not found
    }
}

Example usage:

getSomething({

    "users_id": [1, 2, 3, 18, 24],

    "data_chat_timeread": [0, 0, 0, 0, 0],
    "data_chat_timecurrent": [100, 0, 0, 0, 0],
    "data_chat_counter": [4, 0, 0, 0, 0],

    "data_todo_counter": [2, 0, 0, 0, 0]

}, 18, "users_id", "data_todo_counter");