[javascript] Convert javascript array to string

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?

This question is related to javascript jquery arrays string frontend

The answer is


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


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.


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

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

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

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"


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


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


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


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

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.


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.


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.


Use join() and the separator.

Working example

_x000D_
_x000D_
var arr = ['a', 'b', 'c', 1, 2, '3'];_x000D_
_x000D_
// using toString method_x000D_
var rslt = arr.toString(); _x000D_
console.log(rslt);_x000D_
_x000D_
// using join method. With a separator '-'_x000D_
rslt = arr.join('-');_x000D_
console.log(rslt);_x000D_
_x000D_
// using join method. without a separator _x000D_
rslt = arr.join('');_x000D_
console.log(rslt);
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to frontend

What is {this.props.children} and when you should use it? Vue.js—Difference between v-model and v-bind nodemon command is not recognized in terminal for node js server How to get all the values of input array element jquery Insert HTML with React Variable Statements (JSX) Get form data in ReactJS What is Bootstrap? What are the most common font-sizes for H1-H6 tags Convert javascript array to string good postgresql client for windows?