Alex Rivera | Logout

How to join an associative array into a string

Asked 2012-05-18T20:40:26.733
16

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!

Edit
Report

1 Answer

5

The implementation of functions like Object.map, Object.forEach and so on is still being discussed. For now, you can stick with something like this:

function objectJoin(obj, sep) {
    var arr = [], p, i = 0;
    for (p in obj)
        arr[i++] = obj[p];
    return arr.join(sep);
}

Edit: using a temporary array and joining it instead of string concatenation for performance improvement.

Edit 2: it seems that arr.push(obj[p]); instead of incrementing a counter can actually be faster in most of recent browsers. See comments.

answered 2012-05-18T20:47:03.037

Your Answer