title: Creating object array from key-value pairs
body: <p>From a service I receive a JSON object with key-value pairs, and I need to dynamically create objects from them, grouped by one column. </p>
  
  <p>The JSON looks like this: </p>
  
  <pre><code>[
      { "Group" : "A", "Key" : "Name", "Value" : "John" },
      { "Group" : "A", "Key" : "Age",  "Value" : "30" },
      { "Group" : "A", "Key" : "City", "Value" : "London" },
      { "Group" : "B", "Key" : "Name", "Value" : "Hans" },
      { "Group" : "B", "Key" : "Age",  "Value" : "35" },
      { "Group" : "B", "Key" : "City", "Value" : "Berlin" },
      { "Group" : "C", "Key" : "Name", "Value" : "José" },
      { "Group" : "C", "Key" : "Age",  "Value" : "25" },
      { "Group" : "C", "Key" : "City", "Value" : "Madrid" }
  ]
  </code></pre>
  
  <p>I would need to transform it to the following array of objects:</p>
  
  <pre><code>[
      { Group : "A", Name : "John", Age : 30, City : "London" },
      { Group : "B", Name : "Hans", Age : 35, City : "Berlin" },
      { Group : "C", Name : "José", Age : 25, City : "Madrid" }
  ]
  </code></pre>
  
  <p>Each group can contain any number of key-value pairs.</p>
  
  <p>Currently I have a working solution for this, but I don't know if it's optimal:</p>
  
  <pre><code>var items = [
      { "Group" : "A", "Key" : "Name", "Value" : "John" },
      { "Group" : "A", "Key" : "Age",  "Value" : "30" },
      { "Group" : "A", "Key" : "City", "Value" : "London" },
      { "Group" : "B", "Key" : "Name", "Value" : "Hans" },
      { "Group" : "B", "Key" : "Age",  "Value" : "35" },
      { "Group" : "B", "Key" : "City", "Value" : "Berlin" },
      { "Group" : "C", "Key" : "Name", "Value" : "José" },
      { "Group" : "C", "Key" : "Age",  "Value" : "25" },
      { "Group" : "C", "Key" : "City", "Value" : "Madrid" }
  ], item, record, hash = {}, results = [];
  
  // Create a "hash" object to build up
  for (var i = 0, len = items.length; i &lt; len; i += 1) {
      item = items[i];
  
    if (!hash[item.Group]) {
      hash[item.Group] = {
        Group : item.Group
      };
    }
    hash[item.Group][item.Key] = item.Value;
  }
  
  // Push each item in the hash to the array
  for (record in hash) {
    if(hash.hasOwnProperty(record)) {
      results.push(hash[record]);
    }
  }
  </code></pre>
  
  <p>You can check the fiddle here: <a href="http://jsbin.com/ozizom/1/" rel="nofollow">http://jsbin.com/ozizom/1/</a></p>
  
  <p>Do you have a better solution for this?</p>