189

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
29.6k9 gold badges65 silver badges88 bronze badges
asked Mar 13, 2011 at 12:43
3
  • 7
    what is "value"? Is it an array? If so var str = value.join(', ') might work just fine. Commented Mar 13, 2011 at 12:49
  • 1
    Yes. If I comment out the .get() part, then I get alert boxes which display "id1:val1", "id2:val2" etc . Commented Mar 13, 2011 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.) Commented Mar 13, 2011 at 12:55

13 Answers 13

166

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.

answered Mar 13, 2011 at 13:00
Sign up to request clarification or add additional context in comments.

3 Comments

"Associative array" being a non-JavaScript term for object
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.
@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.
156

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

answered Jul 21, 2011 at 13:07

5 Comments

I would suggest A.toString() instead so it is more clear what you are doing.
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??
you can also join an array like so ['Sunday','Monday','Tuesday','Wednesday','Thursday'].join('');
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.
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.
140

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.

answered Oct 9, 2012 at 23:51

2 Comments

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

answered Mar 29, 2013 at 18:18

Comments

56

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,69919 gold badges32 silver badges39 bronze badges
answered Mar 4, 2016 at 7:46

1 Comment

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

answered Mar 13, 2011 at 12:51

2 Comments

I kind of pasted "cleaned" up code here. I am infact dealing with jquery objects. Thanks, map works perfectly.
@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 :)
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,2824 gold badges29 silver badges53 bronze badges
answered Sep 4, 2012 at 15:41

Comments

3

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);

answered Apr 16, 2023 at 4:01

Comments

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(', '));
answered Mar 13, 2011 at 12:57

Comments

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.

answered Mar 10, 2013 at 20:59

2 Comments

Note that jQuery.param(array) does what encodeGet(array) does.
Note that there is now a native URLSearchParams API for working with search parameters. escape has been deprecated for quite a while.
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'

answered Mar 12, 2023 at 2:28

Comments

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

answered Mar 2, 2018 at 10:58

Comments

-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,9025 gold badges23 silver badges43 bronze badges
answered Jan 13, 2014 at 20:10

1 Comment

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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.