Skip to content Skip to sidebar Skip to footer

Join Associative Arrays In Javascript

I have two (or more) associative arrays in Javascript: tagArray['title'] = ('

title

'); tagArray['text'] = ('

text

'); And want to join them li

Solution 1:

There's no such thing as an "associative array" type in JavaScript. There are Objects and there are Arrays. The Array prototype has a .join() method, but Object does not.

(Objects in general do sort-of work like associative arrays, but there's no explicit functionality built in that mimics actual arrays. You can't find the "length" of an Object instance either, for example.)

You could write such a function however:

functionsmush( o, sep ) {
  var k, rv = null;
  for (k in o) {
    if (o.hasOwnProperty(k)) {
      if (rv !== null) rv += sep;
      rv += o[k];
    }
  }
  return rv;
}

Whether you'd really want to limit the "smush" function to working on direct properties of an object (as opposed to inherited ones), and whether you might want to filter by type, are things you'd have to decide for yourself.

Post a Comment for "Join Associative Arrays In Javascript"