Reorganizing JSON Information

Currently, I am dealing with a JSON file that contains multiple sets of data structured like this:

{"name": ["Adelphi University"], "supp": ["Yes: E, WS"], "ed": ["\u00a0"], "online": ["$40"], "ea": ["12/1"], "mid": ["No"], "rd": ["Rolling"], "recs": ["Yes: CR"], "mail": ["$40"], "schoolr": ["Yes"]}

The intention is for this line to represent a university (hence the name) with other variables like "supp", "online", etc. as attributes of that school. My goal is to restructure this data so that the "name" variable defines the data and the other variables become children of the "name" parent. The desired format of my data should be:

{
  "schools": {
    "Adelphi University": {
      "supp": "Yes: E, WS",
      "ed": "\u00a0",
      "online": "$40",
      "ea": "12/1", 
      "mid": "No", 
      "rd": "Rolling", 
      "recs": "Yes: CR", 
      "mail": "$40", 
      "schoolr": "Yes",    
    },
    "Dartmouth College": { ... },
    "Harvard University": { ... }
  }
}

I am seeking guidance on how to achieve this restructuring. Can someone assist me with this?

Answer №1

To streamline the process, you can loop through the keys and check for the presence of the 'name' key in order to construct an object with the name and assign it to a temporary object. Otherwise, assign the values directly.

var array = [{ "name": ["Adelphi University"], "supp": ["Yes: E, WS"], "ed": ["\u00a0"], "online": ["$40"], "ea": ["12/1"], "mid": ["No"], "rd": ["Rolling"], "recs": ["Yes: CR"], "mail": ["$40"], "schoolr": ["Yes"] }, { "name": ["Dartmouth College"], "supp": ["Yes: E, WS"], "ed": ["\u00a0"], "online": ["$40"], "ea": ["12/1"], "mid": ["No"], "rd": ["Rolling"], "recs": ["Yes: CR"], "mail": ["$40"], "schoolr": ["Yes"] }],
    schools = {},
    result = { schools: schools };

array.forEach(function (a) {
    var temp = {};
    Object.keys(a).forEach(function (k) {
        if (k === 'name') {
            schools[a[k][0]] = temp;
            return;
        }
        temp[k] = a[k][0];
    });
});

console.log(JSON.stringify(result));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

If the object displayed at the beginning is just one of many similar items within an array, you can achieve the desired outcome by implementing the following solution:

var schoolArray = [/** your current json structure **/];
var schools = {};

schoolArray.forEach(function(item) {
  // Check for existence for safety
  var name = item.name[0];
  schools[name] = {};
  delete item.name;
  Object.keys(item).forEach(function(key) {
    // Ensure existence on the right side is also checked
    schools[name][key] = item[key][0];
  });
});

console.log({ schools : schools });  // The desired structure will be outputted

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The styling of MUI components adapts when the Navigate component in React Router is initialized

Incorporating React Router into my application has led to an unexpected side-effect while implementing the <Navigate to="/"> component (which goes to <AthleteHomepage />) upon state change. Currently, I haven't set up dynamic sta ...

Unveiling the information retrieved from an AJAX request during page load

I've been working on a unique concept for my website. Instead of displaying data from a JSON file upon load, I want it to render only when a specific click event occurs. Initially, I tried using callbacks but soon realized the flaws in that approach. ...

React.js Filter Component

I'm currently trying to create a filter for my "localtypes", but I'm encountering an issue where the console in my browser is displaying an empty array. My goal is to access the localtypes properties of the API that I am working with. I attempte ...

Website experiencing issues with moderating Facebook comments

I recently added a Facebook comments box to my website in the footer. Although it is visible, I am unable to moderate it. Furthermore, the comments are not showing up in the comments queue panel at https://developers.facebook.com/tools/comments. I am us ...

I'm consistently encountering issues with my ajax call, does anyone have any suggestions on how to fix

Struggling to grasp JSON concepts with real-life examples. Sadly, every time I run my example code, it returns an error saying [Object object]. I've scoured StackOverflow for solutions but haven't had any luck in getting it to work. What should I ...

Exploring the capabilities of the Javascript Fetch API by making requests for binary Float32Array data with multiple

I need to fetch multiple 32-bit float values from different parts of a large binary file using range requests. This requires specifying multiple ranges in the request. fetch("http://example.com/largeBinaryFile.bin", { headers: { ' ...

Turning an array into JSON using PHP

I'm encountering some difficulty in parsing the data as I attempt to change the shape of the array into JSON format. Here is an example of the current array structure: Array ( [id] => 1 [fisrt_name] => raul [last_name] => gon ...

What is the best way to sort my chat groups based on the most recent update when working with denormalized data in Firebase?

I am currently in the process of creating a chat application using Firebase (along with AngularJS) and my data structure resembles the one outlined on this Firebase documentation page. This setup is great for avoiding unnecessary data retrieval, but I am f ...

Determine the moment when jQuery's load() function completes the loading of several images

My script utilizes jQuery's getScript() function to dynamically retrieve blog posts from Tumblr accounts. The response from the script is a JSON structure called tumblr_api_read, which includes image URLs among other things. function read(blogName) ...

Locate a particular word in every element within an array range (angularjs)

I'm just getting started with learning angularjs and I would appreciate some kindness as a beginner. Currently, I am working on creating a poll app using angular. In my project, I have an array scope named items, which holds all the items to be adde ...

I encountered an issue while iterating through Object HTMLDivElement and applying ChileNode style z-index, resulting in an undefined output in both Firefox and Chrome browsers

function adjustPosition(currentDiv) { try { for (var i = 0; i < document.getElementById("parentContainer").childNodes.length; i++) { document.getElementById("parentContainer").childNodes[i].style.zIndex = 0; ...

utilize ng-include in angularjs to include a page

For some reason, I am having trouble including a file using ng-include. The file is supposed to be included when a button is pressed: <button type="submit" class="btn btn-primary" ng-click="getPartial()">Compare</button> This is the function ...

When an AJAX request is made, it can either return an array or a single object, potentially leading to

My proficiency in Javascript is definitely lacking, and I've only just begun to understand it. I have set up an AJAX call to an API using the GET method. The JSON data returned by the API is pretty standard. If I don't include an ID, I receive ...

Could it be possible that my consecutive POST and GET axios requests are gradually slowing down?

After chaining the POST and GET calls in my code, I noticed a slight slowdown and was curious if this is normal or if there's a more efficient approach. The delay in displaying the google map marker made me think that pushing the newly created marker ...

Tips for eliminating default classes from Mui Typography styling

I’ve been working on creating a Typography element and noticed some default MUI CSS classes added when debugging in the browser. I attempted to disable them by using empty arrays at the end of the sx prop, but it did not work as expected. In the image p ...

Ways to utilize a single HTML page for various URLs while changing one variable value based on the queried URL

My current HTML page structure looks like this: <body ng-controller="DashboardDisplay" onload="submit()"> <div class="container-fluid" > {{scope.arr}} </div> </body> <script> var myApp = angular.module(&apos ...

Unleash the power of Azure Data Factory for transforming JSON documents into SQL Database through unpivoting

Looking to migrate data from DocumentDB to Azure SQL Database. These are the JSON documents: { "DeviceID": "D1", "Time": "2017-07-27T20:00:00", "Temperature": 25, "Humedity": 50 } The structure of the destination SQL database table is (DeviceID | S ...

Managing state in a live chat application

Currently seeking advice on managing state in a real-time messaging/chat app created with VueJS 2. The application is made up of multiple components as shown in the diagram below: https://i.sstatic.net/VGTo8.png Up to this point, I have successfully imp ...

Node functions continue to run smoothly without affecting the loop

I am working on a webdriverjs application and I am trying to determine when jQuery has finished its processes on the page. I have implemented some methods, but it seems that even when the condition is supposed to trigger an else statement and stop the loop ...

Guide on uploading a file to Pinata directly from a React application

I keep encountering the 'MODULE_NOT_FOUND' console error code. Displayed below is the complete console error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f4b4d564b5a4d4d5e4c1251505b5a7f0e110f110f">[email& ...