Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join an associative array into a string

I am trying to do this now and I wonder if there is a "the most used" method to join an associative array (it's values) into a string, delimited by a character.

For example, I have

var AssocArray = { id:0, status:false, text:'apple' };

The string resulted from joining the elements of this object will be

"0, false, 'apple'" or "0, 0, 'apple'"

if we join them with a "," character Any idea? Thanks!

like image 934
ali Avatar asked May 18 '12 20:05

ali


2 Answers

Object.keys(AssocArray).map(function(x){return AssocArray[x];}).join(',');

PS: there is Object.values method somewhere, but it's not a standard. And there are also external libraries like hashish.

like image 162
alex Avatar answered Oct 19 '22 05:10

alex


Just loop through the array. Any array in JavaScript has indices, even associative arrays:

    var AssocArray = { id:0, status:false, text:'apple' };
    var s = "";
    for (var i in AssocArray) {
       s += AssocArray[i] + ", ";
    }
    document.write(s.substring(0, s.length-2));

Will output: 0, false, apple

like image 41
Hidde Avatar answered Oct 19 '22 05:10

Hidde