简体   繁体   中英

Reformat json data using Jquery

I need to convert the following JSON data:

var response = {
   "data":    {
      "List":       [
                  {
            "Name": "Mary",
            "state": "AZ",
            "Matriculation": "complete",
            "Graduation": "complete",
            "Masters": "complete",
            "Phd": "notStarted"
         },
                  {
            "Name": "Stephanie",
            "state": "CT",
            "Matriculation": "complete",
            "Graduation": "complete",
            "Masters": "complete",
            "Phd": "notStarted"
         },
         {
            "Name": "John",
            "state": "CT",
            "Matriculation": "complete",
            "Graduation": "planning",
            "Masters": "notStarted",
            "Phd": "notStarted"
         }]
   }
}

into the following using jQuery:

[ 
   {  
   "state":"AZ",
      "Matriculation":[  
         {  
            "Name":"Mary",
            "status":"complete"
         }
      ],
      "Graduation":[  
         {  
            "Name":"Mary",
            "status":"complete"
         }
      ], 
      "Masters":[  
         {  
            "Name":"Mary",
            "status":"complete"
         }
      ],
      "Phd":[  
         {  
            "Name":"Mary",
            "status":"notStarted"
        }
      ] 
   }, 
   {  
      "state":"CT",
      "Matriculation":[  
         {  
            "Name":"Stephanie",
            "status":"complete"
         },
         {  
            "Name":"John",
            "status":"complete"
         }
      ],
      "Graduation":[  
         {  
            "Name":"Stephanie",
            "status":"complete"
         },
         {  
            "Name":"John",
            "status":"planning"
         }
      ], 
      "Masters":[  
         {  
            "Name":"Stephanie",
            "status":"complete"
         },
         {  
            "Name":"John",
            "status":"notStarted"
         }
      ],
      "Phd":[  
         {  
            "Name":"Stephanie",
            "status":"notStarted"
         },
         {  
            "Name":"John",
            "status":"notStarted"
         }
      ]                 
   }
]

This is what I have tried so far with zero progress. I tried to accomplish this for one state first.

This is the fiddle: http://jsfiddle.net/sqgdyk6f/

Any guidance is appreciated. I am new to JSON manipulation.

Thanks in advance!

First thing you should do is analyze your source format, and your destination format.

  • Your source format is just an array of objects of individual people.

  • Your destination format is an object that groups the people by state and into certain categories.

Next, think about how you can get the source into this destination.

You're going to want to iterate over each individual person in the source, and try to add it to your array of states. Now, I'll say your destination format is a bit peculiar, but by writing a couple of helper functions, you can achieve that format.

Take a look at your destination format again. It's an array of objects. Part of each object in that array is a property called state that has a value for the state that object represents. You're going to want a function that can look through this array for a specific state, and return the existing object for you. If the state doesn't exist, it should add a new entry to the array for you and return that.

Since JSON just means JavaScript Object Notation, and you are actually working with JavaScript objects, you should create an object that models each entry of your destination array. I'm going to call these StateSummary.

function StateSummary(state) {
    this.state = state;
    this.Matriculation = [];
    this.Graduation = [];
    this.Masters = [];
    this.Phd = [];
}

Can you see how this object represents each entry in your destination array?

Now that you have an object that models each entry, we need a function that can check to see if an entry for a certain state already exists. If it exists, it will return that object. If it doesn't exist, it will add a new object to the array, and return this new object.

function addOrGetState(array, state) {
    for (var i = 0; i < array.length; i++) {
        var obj = array[i];

        if (obj.state === state)
            return obj;
    }

    //If the function got here, then it didn't find a matching state.
    var obj = new StateSummary(state);
    array.push(obj); //Add the new object to the array.
    return obj; //Return the new object.
}

So, now you can get an entry by state from your destination array, and you can create new entries.

Go ahead and create a function that will add a person to a StateSummary object.

function addPersonToStateSummary(person, stateSummary) {
    stateSummary.Matriculation.push({ Name: person.Name, status: person.Matriculation });
    stateSummary.Graduation.push({ Name: person.Name, status: person.Graduation});
    stateSummary.Masters.push({ Name: person.Name, status: person.Masters});
    stateSummary.Phd.push({ Name: person.Name, status: person.Phd});
}

The last piece is iterating over the source array, and massaging that data into your destination array.

var sourceArray = response.data.List; //You provided this.
var destinationArray = []; //Allocate a new array to put stuff in.

for (var i = 0; i < sourceArray.length; i++) {
    var person = sourceArray[i]; //Each entry of the source array represents a person.

    var stateSummary = addOrGetState(destinationArray, person.state);

    addPersonToStateSummary(person, stateSummary);
}

This should give you what you are looking for. I hope this breakdown teaches you how to think about the problem in an analytical way, breaking its steps down first, and then solving them with code.

Here is a demo:

 var response = { "data": { "List": [{ "Name": "Mary", "state": "AZ", "Matriculation": "complete", "Graduation": "complete", "Masters": "complete", "Phd": "notStarted" }, { "Name": "Stephanie", "state": "CT", "Matriculation": "complete", "Graduation": "complete", "Masters": "complete", "Phd": "notStarted" }, { "Name": "John", "state": "CT", "Matriculation": "complete", "Graduation": "planning", "Masters": "notStarted", "Phd": "notStarted" }] } }; function StateSummary(state) { this.state = state; this.Matriculation = []; this.Graduation = []; this.Masters = []; this.Phd = []; } function addOrGetState(array, state) { for (var i = 0; i < array.length; i++) { var obj = array[i]; if (obj.state === state) return obj; } //If the function got here, then it didn't find a matching state. var obj = new StateSummary(state); array.push(obj); //Add the new object to the array. return obj; //Return the new object. } function addPersonToStateSummary(person, stateSummary) { stateSummary.Matriculation.push({ Name: person.Name, status: person.Matriculation }); stateSummary.Graduation.push({ Name: person.Name, status: person.Graduation }); stateSummary.Masters.push({ Name: person.Name, status: person.Masters }); stateSummary.Phd.push({ Name: person.Name, status: person.Phd }); } var sourceArray = response.data.List; //You provided this. var destinationArray = []; //Allocate a new array to put stuff in. for (var i = 0; i < sourceArray.length; i++) { var person = sourceArray[i]; //Each entry of the source array represents a person. var stateSummary = addOrGetState(destinationArray, person.state); addPersonToStateSummary(person, stateSummary); } document.getElementById('result').innerHTML = JSON.stringify(destinationArray); 
 <div id="result"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM