Last active
October 9, 2016 22:55
-
-
Save Sylvestre67/39023f2370902f0621be1be928c72880 to your computer and use it in GitHub Desktop.
pivoting_rows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /****** | |
| d3.csv is d3 function quite usefull when it comes to retrieve data from a csv file. | |
| It parses the csv and return a list object, each object corresponding to one rows in the original file. | |
| See: https://github.com/d3/d3-3.x-api-reference/blob/master/CSV.md#csv | |
| ******/ | |
| d3.csv('rows.csv',function(rows){ | |
| /****** | |
| For the sake of this example, here's the object return by d3.csv: | |
| rows = [{person_id:"122", question_id:"A", answer:"ABC"}, | |
| {person_id:"122", question_id:"B", answer:"DEF"}, | |
| {person_id:"122", question_id:"C", answer:"GHI"}, | |
| {person_id:"344", question_id:"A", answer:"JKL"}, | |
| {person_id:"344", question_id:"B", answer:"MNO"}, | |
| {person_id:"344", question_id:"C", answer:"PQR"}, | |
| {person_id:"455", question_id:"A", answer:"STU"}, | |
| {person_id:"455", question_id:"B", answer:"VW"}, | |
| {person_id:"455", question_id:"C", answer:"XYZ"}]; | |
| ******/ | |
| var pivoted_rows = {}; | |
| rows.forEach(function(row){ | |
| // If current person does not have a key on the pivoted_rows object, add it and assign an empty list to it. | |
| (pivoted_rows[row.person_id] === undefined) | |
| ? pivoted_rows[row.person_id] = [] | |
| : false; | |
| // For each row, add each question and given answer to their corresponding person_id. | |
| pivoted_rows[row.person_id].push({"question" : row.question_id, "answer" : row.answer }); | |
| }); | |
| /****** | |
| pivoted_rows is now: | |
| pivoted_rows = {122: [{answer: "ABC", question: "A"},{answer: "DEF",question: "B"},{answer: "GHI",question: "C"}], | |
| 344: [{answer: "JKL",question: "A"}, {answer: "MNO",question: "B"},{answer:"PQR",question:"C"}], | |
| 455: [{answer: "PQR",question: "A"}, {answer:"VW",question:"B"}, {answer:"XYZ",question:"C"}]} | |
| ******/ | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment