SBB SBB - 7 months ago 13
Javascript Question

jQuery check if value is in object

I have a page with user accounts and check boxes. On save, I need to add all the values of the check boxes to an object as long as they don't already exist in there.

I had this working when I was using an associative array as I was only storing a single value at the time. I am now storing it as an object and I need to make sure the QID (this is unique) doesn't already exist in the object.

Is there an elegant way to approach this?

var selectedUsers = [];

$(tab).find(".cb:checked").each(function() {
// If the QID is not already in the array, add it
if(jQuery.inArray($(this).val(), selectedUsers) === -1) {
selectedUsers.push({
"qid": $(this).val(),
"first": $(this).data('emp_first'),
"last": $(this).data('emp_last'),
"department": $(this).data('emp_dept')
});
}
});

Answer

Just keep a map that you add the ID's to, that way it's easy and efficient to check if an ID exist, regardless of the data structure in the array

var selectedUsers = [];
var addedUsers    = {};

$(tab).find(".cb:checked").each(function() {

    var qid = this.value;

    if ( !(qid in addedUsers) ) {
       selectedUsers.push({
          qid   : qid,
          first : $(this).data('emp_first'),
          last  : $(this).data('emp_last'),
          department : $(this).data('emp_dept')
       });
       addedUsers[qid] = 'x';
    }
});