Note that there are some explanatory texts on larger screens.

plurals
  1. POPivot json data from array of models
    text
    copied!<p>I host a web api service, which returns a snapshot of my model "myModel" for the last 12 months. The json array that I receive on my client is a simple array of 12 "myMydel" objects.</p> <p>If myModel has properties "foo" and "bar", is there an efficient way in javascript to pivot the array to result in a collection of arrays of properties, for example:</p> <p><em>i'd like to transform</em></p> <pre><code>history{ myModel[] myModel[0] foo: 1 bar: 2 Key: 1 myModel[1] foo: 3 bar: 4 Key: 1 } </code></pre> <p><em>into</em></p> <pre><code>history{ "1"{ //key foo[] foo[0]: 1 foo[1]: 3 bar[] bar[0]: 2 bar[1]: 4 } } </code></pre> <p>I am open to implementing on the server side if that would be more efficient. My api service is a .NET 4.5 Web Api.</p> <p>So again. My question is, is there a super efficient way to achieve these results in javascript? If not, is there one in c#? Can someone provide some simple example code to get me going?</p> <p>Help is much appreciated. Thanks!</p> <p><strong>EDIT: Working code</strong></p> <p>Even though I was voted down on this, i figure I'd provide a working example of javascript that achieves this. It's pretty fast too. Note that each history record must have a Key to group records by.</p> <pre><code> _pivot = function(history) { var i, pivoted, prop, rec; pivoted = {}; if (history !== null) { i = 0; while (i &lt; history.length) { rec = history[i]; pivoted[rec.Key] = pivoted[rec.Key] || {}; for (prop in rec) { pivoted[rec.Key][prop] = pivoted[rec.Key][prop] || []; if (!pivoted[rec.Key][prop].date) { pivoted[rec.Key][prop].push({ value: rec[prop] }); } } i++; } return pivoted; } return null; }; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload