views:

189

answers:

1

Given an associative array (of the sort returned by jQuery.serializeArray()) like this:

[
{ 'name': 'abc', 'value': 'aaa', '__proto__': [Object] },
{ 'name': 'def', 'value': 'bbb', '__proto__': [Object] },
{ 'name': 'abc', 'value': 'ccc', '__proto__': [Object] }
]

How can one convert this, using either jQuery or just javascript, to an associative array of name: [values] like this:

{
   'abc': ['aaa', 'ccc'],
   'def': ['bbb']
}

This seems to essentially be the inverse of this question: Build associative array based on values of another associative array... but in Javascript (not PHP). I wasn't able to find this question on Stackoverflow, though I thought it would have been asked.

Thank you for reading.

Brian

+2  A: 

You just have to iterate over the objects, check if the name exist on the result, and store or push the value, e.g.:

var result = {};
$.each(arr, function (index, el) {
  if (!result[el.name]) {
    result[el.name] = [el.value];
  } else {
    result[el.name].push(el.value);
  }
});
//{"abc":["aaa","ccc"], "def":["bbb"]}
CMS
@CMS: Thank you; that'll do it. :) It crossed my mind, since it seemed such a common operation, that there may be something built into jQuery to do this (e.g. $.map/merge), or some set_default (like Python) to avoid the if/else.
Brian M. Hunt