I am trying to join the values of an object/associative array to make changes to my code easier but I can't figure out how to properly join them. Here is my code:
$( document ).on( "click", ".taskstatus a", function ( event ) {
event.preventDefault();
classes = {
'OPEN': 'state_open',
'COMPLETED': 'state_completed',
'SKIPPED': 'state_skipped',
'REJECTED': 'state_rejected'
};
joinedClasses = classes.map(function(value, key){ return key; }).join(' ');
state = $(this).data('state');
taskID = $(this).closest('.task').attr('id').replace( 'task_', '' );
// Update checkbox icon
$(this).closest('.taskwrap').find('.taskcheckbox').data( 'icon', $(this).data('icon') );
// Update task class
alert( joinedClasses );
$(this).closest('.task').removeClass( joinedClasses ).addClass( classes[state] );
});
This code breaks at the map function since it doesn't see it as an array, whats the best way to accomplish joining the values of class so that they look like this: "state_open state_completed state_skipped state_rejected"?
The join() method joins the elements of an array into a string, and returns the string. The elements will be separated by a specified separator. The default separator is comma (,). Show activity on this post.
The jQuery. extend() method is used to merge contents of two or more objects together. The object is merged into the first object.
You can use jQuery.map function. It is more forgiving and therefore allows usage on an associative array (like yours) as well as a traditional array:
joinedClasses = $.map(classes, function(e){
return e;
});
result:
["state_open", "state_completed", "state_skipped", "state_rejected"]
live example: http://jsfiddle.net/MK4f7/
this can then be joined using a space in the same way as your original:
joinedClasses = $.map(classes, function(e){
return e;
}).join(' ');
Since it's not an array you can use map. You need to use a for loop like below:
var classes = {
'OPEN': 'state_open',
'COMPLETED': 'state_completed',
'SKIPPED': 'state_skipped',
'REJECTED': 'state_rejected'
};
// Create a tmp array for the join
var joined = [];
// Loop over the object Literal.
// the var key is now the prop in the object.
for (var key in classes) {
var val = classes[key]; // gets the value by looking for the key in the object
joined.push(val);
}
// Join the array with a space.
joined = joined.join(' ');
Working fiddle
EDIT: accepted answer is better if you want to do it with jQuery, cheers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With