Unfolding array of values into distinct categories

81 views Asked by At

I have a JSON object(array) coming from a sharepoint table and I need to restructure the rows, but having a bit of a struggle (I'm fairly beginner in JS).

I have something like this:

   [{'ID':'1', 'Title': 'First record', 'blue':'3', 'red':'6', 'yellow':'2'},
    {'ID':'2', 'Title': 'Second record', 'blue':'1', 'red':'3', 'yellow':'6'}]

and I need to transform it into:

   [{'ID':'1', 'Title': 'First record', 'category':'blue', 'count':'3'},

    {'ID':'1', 'Title': 'First record', 'category':'red', 'count':'6'},

    {'ID':'1', 'Title': 'First record', 'category':'yellow', 'count':'2'},

    {'ID':'2', 'Title': 'Second record', 'category':'blue', 'count':'1'},

    {'ID':'2', 'Title': 'Second record', 'category':'red', 'count':'3'},

    {'ID':'2', 'Title': 'Second record', 'category':'yellow', 'count':'6'}]

What I'm trying to achieve:

  1. Create separate rows to 'unlold' three category fields (blue, red, yellow), so one row becomes three
  2. Preserve other fields in each newly created row (ID, Title)

I'm trying to reformat this data so that I can feed the array into Dimple/D3 chart to create a categorised chart showing value counts for each category.

I tried doing for...each and doing loops inside of loops and _.map from examples I've found, but not getting the output I'm after (debugging in browser is a pain, so not sure where the code fails for me :/ ). Would you be so kind as to show an example of how to do this manipulation properly (probably Underscore's .chain .each and .map)? Preferably without arrow functions (I need to make it work in IE11).

Thank you in advance!

1

There are 1 answers

0
ashok19r91d On

It can be done by rebuilding new object collection; here is a sample;

var myData = JSON.parse('JsonString');
var transformedData = [];
myData.forEach(function(data){
    transformedData.push({ ID: data.ID, Title: data.Title, category: "blue", count = data.blue });
    transformedData.push({ ID: data.ID, Title: data.Title, category: "red", count = data.red });
    transformedData.push({ ID: data.ID, Title: data.Title, category: "yellow", count = data.yellow });
});
var transformedJson = JSON.stringify(transformedData);

Remember JSON names should use double quotes " not single quotes '.