181

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?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Neo
  • 13,179
  • 18
  • 55
  • 80
  • 6
    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

13 Answers13

161

If value is not a plain 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);
});
console.log(blkstr.join(", "));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

(output will appear in the dev console)

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

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
  • “Associative array” being a non-JavaScript term for object – Heretic Monkey Jul 26 '21 at 20:26
  • A JavaScript object is not a JavaScript Array. You should probably inform people that this is not the correct answer to the question because the question was asked incorrectly and the user meant associative array, but for me, it's not what I searched for. – Cale McCollough Sep 09 '22 at 17:11
  • @CaleMcCollough the question author had no idea how this is called back when asking, and neither did I. As the other comment here correctly says, “Associative array” is also incorrect as it refers to abstract data structure. In JavaScript, every object is an associative array, including plain array. So to make it more simple I just used "not a plain array" and I stand by this definition. And the answer is correct, it iterates the keys, and collecting the data into plain array that is later converted to string. – Shadow The GPT Wizard Sep 09 '22 at 18:03
153

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. :)

Spiderman
  • 1,969
  • 1
  • 14
  • 14
  • 16
    I would suggest A.toString() instead so it is more clear what you are doing. – Justin Feb 19 '14 at 20:41
  • 18
    If you do `[1,2,[3]].toString()`, you'll get `1,2,3`, which is pretty rubbish. This answer is just a worse way to write the same call to the same broken, native string method. 42 upvotes?? – Carl Smith Jun 13 '14 at 22:53
  • 18
    you can also join an array like so `['Sunday','Monday','Tuesday','Wednesday','Thursday'].join('');` – etoxin Dec 14 '14 at 23:30
  • 3
    `Array.join()` is definitely the best option, since it won't simply concatenate values with commas, but allow the user to determine how the concatenation should be done. You could use comma+blankspace for example. – Felipe Leão May 24 '16 at 19:01
  • 1
    This is perfect for me. I'm passing in an array which gets changed to a string separated by commas no spaces for an api call. Thanks again. – Nick D Aug 13 '17 at 07:35
137

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

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

Or, set the separator with array.join('; '); // result: a; b; c.

Justin
  • 26,443
  • 16
  • 111
  • 128
  • 4
    I was just hoping for the array to be literally translated into a string and for me to then be forced to use Regex to trim off the fat, but this is Oh So Much Better! Thanks Justin. – cranberry Jan 22 '14 at 02:53
  • 1
    But that's not the case in the question, it's not about plain arrays. `.toString()` of object which isn't plain array would give "object", or something like that. – Shadow The GPT Wizard Sep 09 '22 at 18:05
106

not sure if this is what you wanted but

var arr = ["A", "B", "C"];
var arrString = arr.join(", ");

This results in the following output:

A, B, C

Nicholas
  • 5,430
  • 3
  • 21
  • 21
53

Four methods to convert an array to a string.

Coercing to a string

var arr = ['a', 'b', 'c'] + [];  // "a,b,c"

var arr = ['a', 'b', 'c'] + '';  // "a,b,c"

Calling .toString()

var arr = ['a', 'b', 'c'].toString();  // "a,b,c"

Explicitly joining using .join()

var arr = ['a', 'b', 'c'].join();  // "a,b,c" (Defaults to ',' seperator)

var arr = ['a', 'b', 'c'].join(',');  // "a,b,c"

You can use other separators, for example, ', '

var arr = ['a', 'b', 'c'].join(', ');  // "a, b, c"

Using JSON.stringify()

This is cleaner, as it quotes strings inside of the array and handles nested arrays properly.

var arr = JSON.stringify(['a', 'b', 'c']);  // '["a","b","c"]'
CDspace
  • 2,639
  • 18
  • 30
  • 36
VIJAY P
  • 1,363
  • 1
  • 12
  • 14
  • 1
    JSON.stringify also makes a single value look like a proper array and not a string: `[8]` vs `8`. That would be the top answer if I had all the votes. Thanks for mentioning it. – Noumenon Nov 12 '20 at 22:49
17

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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 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
3

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')? ' ] ':' } ');;
}
Ruchit Rami
  • 2,273
  • 4
  • 28
  • 53
buitanan
  • 39
  • 2
2
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(', '));
S L
  • 14,262
  • 17
  • 77
  • 116
2

if you want to go with plain java script

  const strArr = ['h', 'e', 'l', 'l','o'];

  const str = strArr.toString().split(",").join("");

  console.log(str);
1

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.

Fydo
  • 1,396
  • 16
  • 29
  • 1
    Note that jQuery.param(array) does what encodeGet(array) does. – Curtis Yallop Sep 06 '13 at 23:45
  • Note that there is now a native [`URLSearchParams` API](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) for working with search parameters. `escape` has been deprecated for quite a while. – Heretic Monkey Dec 12 '22 at 16:30
0

We can do this using following javascript methods

using join(): while we use join we can able to provide space between the itme and comma

using toString(): If we use join do don't any space between the item and comma

const array = [1,2,3,4,5]

console.log(array.join(', ')) // '1, 2, 3, 4, 5'

console.log(array.toString()) // '1,2,3,4,5'
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
-1

You shouldn't confuse arrays with lists.

This is a list: {...}. It has no length or other Array properties.

This is an array: [...]. You can use array functions, methods and so, like someone suggested here: someArray.toString();

someObj.toString(); will not work on any other object types, like lists.

shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34
Pedro Ferreira
  • 493
  • 7
  • 14
  • That's not a "list"; that's an object. And using, e.g., `{ "alpha", 34, { obj: "ect" } }` does not produce a "list"; it produces (depending on where and how) a syntax error or the object `{ obj: "ect" }`. Whereas, using `[ "alpha", 34, { obj: "ect" } ]` will produce an array with three items; a string, a number, and an object, no matter where it is used. – Heretic Monkey Dec 12 '22 at 16:37
-1

Here's an example using underscore functions.

var exampleArray = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
var finalArray = _.compact(_.pluck(exampleArray,"name")).join(",");

Final output would be "moe,larry,curly"

sabin
  • 841
  • 12
  • 15