2

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.

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:

i'd like to transform

history{
  myModel[]
     myModel[0]
       foo: 1
       bar: 2
       Key: 1
     myModel[1]
       foo: 3
       bar: 4
       Key: 1
 }

into

history{
    "1"{  //key
      foo[] 
        foo[0]: 1
        foo[1]: 3
      bar[]
         bar[0]: 2
         bar[1]: 4
      }
  }

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.

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?

Help is much appreciated. Thanks!

EDIT: Working code

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.

  _pivot = function(history) {
    var i, pivoted, prop, rec;
    pivoted = {};
    if (history !== null) {
      i = 0;
      while (i < 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;
  };
kmehta
  • 2,457
  • 6
  • 31
  • 37

1 Answers1

1

Well, as far as super efficient, I think unless you change your underling model, you are going to have to just iterate through your model, either server side or client side and assign each property to a different array.

var tempFoo = newArray(); tempBar = newArray();
for (var i = 0; i < myModel.length; i++){
    tempFoo.push(myModel[i].foo);
    tempBar.push(myModel[i].bar);
}

Also, if you have it sorted in your server side code, or if it is just automatically sorted from whatever database you are pulling from, you will see speed increases. Why is it faster to process a sorted array than an unsorted array?

Hope this helps, fyi, the example is Javascript.

V/R

Community
  • 1
  • 1
Rouse02
  • 157
  • 2
  • 7