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!

Ash Burlaczenko
  • 24,778
  • 15
  • 68
  • 99
ali
  • 10,927
  • 20
  • 89
  • 138
  • 1
    There's no built-in method to do that; just write a short piece of code. Be aware that the ordering of the properties as returned by a `for ... in` loop will not be predictable, so if you want to impose some canonical way of ordering the values you'll have to think up something yourself. – Pointy May 18 '12 at 20:42

3 Answers3

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

alex
  • 11,935
  • 3
  • 30
  • 42
  • 2
    I really like one-liners, but you have to keep two things in mind: it doesn't work for IE<9, and using `map` can be slow for very large object. – MaxArt May 18 '12 at 20:49
  • 1
    1) it does work for IE<9 with compatibility libraries; 2) string concatenation is slow too... so for really large objects you have to use completely another approach like streams in node.js (but really, that's not in the question) – alex May 18 '12 at 20:54
  • 1
    ali never told anything about using other libraries, but anyway, calling functions is way slower than string concatenation, and even if you don't want to concatenate strings you can always use temporary arrays and use `join` in the end. – MaxArt May 18 '12 at 20:59
9

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

Hidde
  • 11,493
  • 8
  • 43
  • 68
  • 1
    'i in AssocArray' should be 'var i in AssocArray' so that it doesn't pollute the global namespace. – pseudosavant May 18 '12 at 20:49
  • Very true, the kind of thing I didn't take into account in this example. – Hidde May 18 '12 at 21:34
  • Maybe you should add a check using 'hasOwnProperty' like this: `for (var i in AssocArray) { **if (AssocArray hasOwnProperty(i))** s += AssocArray[i] + ", "; }` See: http://stackoverflow.com/questions/921789/how-to-loop-through-plain-javascript-object-with-objects-as-members – Djibril NDIAYE May 12 '17 at 23:03
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.

MaxArt
  • 22,200
  • 10
  • 82
  • 81
  • is there a reason you aren't just using `arr.push(obj[p])` instead of `arr[i++] = obj[p]`? – pseudosavant May 21 '12 at 16:56
  • That's because even if `push` is a very fast function, it's a functions nonetheless, and calling a function is time expensive. Many browsers have special optimization for it nowadays, but that isn't always the case. Another technique consists in dimensioning the array before assigning its elements with `new Array(lentgh)`, in order to avoid redimensioning it, but it can be done only if `length` is known, and this isn't the case. – MaxArt May 21 '12 at 17:19
  • 1
    Sounds like a premature optimization. Looks like performance between these two methods varies a lot, and the 'best' way depends on the browser used. Check out this jsperf example: http://jsperf.com/array-increment-vs-array-push – pseudosavant May 21 '12 at 22:49
  • Nice one, I was sure some optimization steps were made. I'm actually surprised they went that far. A year ago the results were quite different. – MaxArt May 21 '12 at 22:53
  • It seemed to vary a lot based on exactly how it was constructed. The slowest method was still millions of ops/sec though, so it is unlikely to be a real performance issue for most code. Also, depending on exactly how the code was expressed changed which browser was the fastest; Chrome, IE, and Firefox were all at the top for various versions. Making sure the result of the loop was used seem to make it 'better', but this is always the problem with JS micro-benchmarks since code paths can be determined to be doing nothing ultimately. – pseudosavant May 21 '12 at 23:53