Convert javascript array to string

JavascriptJqueryArraysString

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

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.

Solution 4 - Javascript

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

Solution 5 - Javascript

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

Solution 6 - Javascript

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.

Solution 7 - Javascript

Use join() and the separator.

Working example

var arr = ['a', 'b', 'c', 1, 2, '3'];

// using toString method
var rslt = arr.toString(); 
console.log(rslt);

// using join method. With a separator '-'
rslt = arr.join('-');
console.log(rslt);

// using join method. without a separator 
rslt = arr.join('');
console.log(rslt);

Solution 8 - Javascript

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')? ' ] ':' } ');;
}

Solution 9 - Javascript

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(', '));

Solution 10 - Javascript

I needed an array to became a String rappresentation of an array I mean I needed that

var a = ['a','b','c'];
//became a "real" array string-like to pass on query params so was easy to do:
JSON.stringify(a); //-->"['a','b','c']"

maybe someone need it :)

Solution 11 - Javascript

const myArray=["hello",4,"programming"];
console.log(myArray.join(''));//hello4programming

We can use the join function for converting

Solution 12 - Javascript

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.

Solution 13 - Javascript

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.

Solution 14 - Javascript

>Array.prototype.toString() > >The toString() method returns a string representing the specified array and its elements. > > var months = ["Jan", "Feb", "Mar", "Apr"]; > months.toString(); // "Jan,Feb,Mar,Apr" > >Syntax > > arr.toString() > >Return value > >A string representing the elements of the array.

for more information :

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toString

Solution 15 - Javascript

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"

Solution 16 - Javascript

If you are looking for the first member to extract or the array has just one member, do this:

var months = ["Jan", "Feb", "Mar", "Apr"];
months.shift(); // "Jan"

Solution 17 - Javascript

we can use the function join() to make the string from the array, and as parameter of function join we giv it '' empty character.

var newStr =mArray.join('');

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNeoView Question on Stackoverflow
Solution 1 - JavascriptShadow Wizard Says No More WarView Answer on Stackoverflow
Solution 2 - JavascriptSpidermanView Answer on Stackoverflow
Solution 3 - JavascriptJustinView Answer on Stackoverflow
Solution 4 - JavascriptNicholasView Answer on Stackoverflow
Solution 5 - JavascriptVIJAY PView Answer on Stackoverflow
Solution 6 - JavascriptFelix KlingView Answer on Stackoverflow
Solution 7 - JavascriptDeepu ReghunathView Answer on Stackoverflow
Solution 8 - JavascriptbuitananView Answer on Stackoverflow
Solution 9 - JavascriptSantosh LinkhaView Answer on Stackoverflow
Solution 10 - JavascriptMagicoView Answer on Stackoverflow
Solution 11 - JavascriptForce BoltView Answer on Stackoverflow
Solution 12 - JavascriptFydoView Answer on Stackoverflow
Solution 13 - JavascriptPedro FerreiraView Answer on Stackoverflow
Solution 14 - JavascriptKARTHIKEYAN.AView Answer on Stackoverflow
Solution 15 - JavascriptsabinView Answer on Stackoverflow
Solution 16 - JavascriptM.RezaView Answer on Stackoverflow
Solution 17 - JavascriptAmirouche ZeggaghView Answer on Stackoverflow