Search code examples
javascriptjqueryjquery-templates

jQuery tmpl if object value == current iteration value


SelectedPlayersI'm doing some work on a site which is using jQuery templates.

I have a JSON object:

var data = [{
   "CoachingSessionActivityID": 1,
   "PlayersInTeams": [{"PlayerID": 1, "PlayerName": "Some Name"},{"PlayerID": 2, "PlayerName": "Another Name"}],
   "SelectedPlayers":[{"PlayerID": 1, "PlayerName": "Some Name"}]
},{
   "CoachingSessionActivityID": 2,
   "PlayersInTeams": [{"PlayerID": 1, "PlayerName": "Some Name"},{"PlayerID": 2, "PlayerName": "Another Name"}],
   "SelectedPlayers":[{"PlayerID": 1, "PlayerName": "Some Name"}]
}];

I'm trying to mark a select option (powered by Bootstrap-Multiselect) as selected if the current iteration PlayerID is in the selected players object.

 <select id="playersList_${CoachingSessionActivityID}" class="form-control players-list"  multiple="multiple" name="playersList">
                    {{each(PlayerID, PlayerName) PlayersInTeams}}
                        {{if checkForValue(SelectedPlayers == PlayerID)}}
                            <option value="${PlayerID}" selected="selected">${PlayerName}</option>
                        {{else}}
                            <option value="${PlayerID}">${PlayerName}</option>
                        {{/if}}
                    {{/each}}
                </select>

I'm using this function to identify whether a player is within the selected list:

 function checkForValue(json, value) {

            for (key in json) {
                if (typeof (json[key]) === "object") {
                    return checkForValue(json[key], value);
                } else if (json[key] == value) {
                    return true;
                }
            }
            return false;
        }

Problem

The problem is only 1 item is being identified as being a selected value. Our actual data has 150 players in "PlayersInTeams" and some coaching sessions have over 20 selected players.

Any ideas?


Solution

  • @Arunraj was right, my function was ending when it returned true obviously so it wasn't iterating the complete list.

    I found the answer from this answer: https://stackoverflow.com/a/19302725/1888402

    Essentially using obj.some(...) with the following function:

    function hasValue(obj, key, value) {
        return obj.hasOwnProperty(key) && obj[key] === value;
    }
    

    In the scope of the question, the solution was:

      {{each(PlayerID, PlayerName) PlayersInTeams}}
          {{if SelectedPlayers.some(function(player){ return hasValue(player, "PlayerID", PlayerID)}) }}
               <option value="${PlayerID}" selected="selected">${PlayerName}</option>
          {{else}}
               <option value="${PlayerID}">${PlayerName}</option>
           {{/if}}
       {{/each}}