Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenating strings in .each loop

This may be a dumb question but I can't seem to get it or find it anywhere.

I have a .each function that returns the id's of a bunch of divs on a page and then assigns them a number. I need them to be outputted in a specific format all as one string so I can pass them to a database and use them as "sort_order" values. (I split them through a sproc in my database).

Here is my code:

jQuery('#updateAllContentButton').click(function() {
    var count = 1;
 jQuery('.CommentaryItem').each(function() {
    var id = GetID(jQuery(this));
        var data_str = (id + ':' + count + '~');
        console.log(data_str);
        count++;
    });
});

So that returns each data_str on a separate line but I need it to return it like this: 144:2~145:3~146:4~147:4~148:5 (so on)

Any help would be appreciated, thanks!

like image 475
J215D Avatar asked Dec 20 '22 03:12

J215D


1 Answers

Use map and join :

jQuery('#updateAllContentButton').click(function() {
    console.log(jQuery('.CommentaryItem').map(function(i) {
        return GetID(jQuery(this)) + ':' + (i+1);
    }).get().join('~'));
});

Note that you don't have to count yourself : Most jQuery iteration functions do it for you.

like image 98
Denys Séguret Avatar answered Jan 01 '23 16:01

Denys Séguret