Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to iterate over a "value" list and convert it into a string. Here is the code:

var blkstr = $.each(value, function(idx2,val2) {                    
     var str = idx2 + ":" + val2;
     alert(str);
     return str;
}).get().join(", ");    

alert() function works just fine and displays the proper value. But somehow, jquery's .get() function doesn't get the right sort of object and fails. What am I doing wrong?

share|improve this question
3  
what is "value"? Is it an array? If so var str = value.join(', ') might work just fine. – StefanS Mar 13 '11 at 12:49
Yes. If I comment out the .get() part, then I get alert boxes which display "id1:val1", "id2:val2" etc . – Neo Mar 13 '11 at 12:51
Do you mean "...get the right sort of object"? (A quick proofread before clicking Ask Question is usually a good idea.) (I removed my earlier comment which was rather more strongly put -- this question has a lot fewer typos and such than many.) – T.J. Crowder Mar 13 '11 at 12:55

8 Answers

up vote 21 down vote accepted

If value is associative array, such code will work fine:

var value = { "aaa": "111", "bbb": "222", "ccc": "333" };
var blkstr = [];
$.each(value, function(idx2,val2) {                    
     var str = idx2 + ":" + val2;
     blkstr.push(str);
});
alert(blkstr.join(", "));

As Felix mentioned, each() is just iterating the array, nothing more.

Live test case.

share|improve this answer

Converting From Array to String is So Easy !

var A = ['Sunday','Monday','Tuesday','Wednesday','Thursday']
array = A + ""

That's it Now A is a string. :)

share|improve this answer
That seems like cheating...but it works! :) – BWDesign Apr 4 at 15:59
It only works IF you want each item separated by a comma – Dan Apr 25 at 17:35

jQuery.each is just looping over the array, it doesn't do anything with the return value. You are looking for jQuery.map (I also think that get() is unnecessary as you are not dealing with jQuery objects):

var blkstr = $.map(value, function(val,index) {                    
     var str = index + ":" + val;
     return str;
}).join(", ");  

DEMO


But why use jQuery at all in this case? map only introduces an unnecessary function call per element.

var values = [];

for(var i = 0, l = value.length; i < l; i++) {
    values.push(i + ':' + value[i]);
}

// or if you actually have an object:

for(var id in value) {
    if(value.hasOwnProperty(id)) {
        values.push(id + ':' + value[id]);
    }
}

var blkstr = values.join(', ');

∆: It only uses the return value whether it should continue to loop over the elements or not. Returning a "falsy" value will stop the loop.

share|improve this answer
+1 I like it a lot! – alex Mar 13 '11 at 12:53
I kind of pasted "cleaned" up code here. I am infact dealing with jquery objects. Thanks, map works perfectly. – Neo Mar 13 '11 at 13:00
@Neo: You only need map if value is a jQuery object. And then you should use value.map(...).get(). But if you just have an array of jQuery objects, then you need no get. You're welcome :) – Felix Kling Mar 13 '11 at 13:07

this's my function, convert object or array to json

function obj2json(_data){
    str = '{ ';
    first = true;
    $.each(_data, function(i, v) { 
        if(first != true)
            str += ",";
        else first = false;
        if ($.type(v)== 'object' )
            str += "'" + i + "':" + obj2arr(v) ;
        else if ($.type(v)== 'array')
            str += "'" + i + "':" + obj2arr(v) ;
        else{
            str +=  "'" + i + "':'" + v + "'";
        }
    });
    return str+= '}';
}

i just edit to v0.2 ^.^

 function obj2json(_data){
    str = (($.type(_data)== 'array')?'[ ': '{ ');
    first = true;
    $.each(_data, function(i, v) { 
        if(first != true)
            str += ",";
        else first = false;
        if ($.type(v)== 'object' )
            str += '"' + i + '":' + obj2json(v) ;
        else if ($.type(v)== 'array')
            str += '"' + i + '":' + obj2json(v) ;
        else{
            if($.type(_data)== 'array')
                str += '"' + v + '"';
            else
                str +=  '"' + i + '":"' + v + '"';
        }
    });
    return str+= (($.type(_data)== 'array')? ' ] ':' } ');;
}
share|improve this answer

You can also use .toString() to join an array with a comma.

var array = ['a', 'b', 'c'];
array.toString();

The result would be: a,b,c

See: http://www.w3schools.com/jsref/jsref_tostring_array.asp

share|improve this answer
var arr = new Array();

var blkstr = $.each([1, 2, 3], function(idx2,val2) {                    
    arr.push(idx2 + ":" + val2);
    return arr;
}).join(', ');

console.log(blkstr);

OR

var arr = new Array();

$.each([1, 2, 3], function(idx2,val2) {                    
    arr.push(idx2 + ":" + val2);

});

console.log(arr.join(', '));
share|improve this answer

convert an array to a GET param string that can be appended to a url could be done as follows

function encodeGet(array){
    return getParams = $.map(array , function(val,index) {                    
        var str = index + "=" + escape(val);
        return str;
   }).join("&");
}

call this function as

var getStr = encodeGet({
    search:     $('input[name="search"]').val(),
    location:   $('input[name="location"]').val(),
    dod:        $('input[name="dod"]').val(),
    type:       $('input[name="type"]').val()
});
window.location = '/site/search?'+getStr;

which will forward the user to the /site/search? page with the get params outlined in the array given to encodeGet.

share|improve this answer

not sure if this is what you wanted but

var arr = [A, B, C];
var arrString = arr.join("");
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.