7

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"?

3 Answers 3

20

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(' ');
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

If you can load linq.js, try this code:

joinedClasses = Enumerable.From(classes).Select("$.Value").ToArray().join(' ');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.