converting a JSON array into an object

I seem to be facing a challenge:

I have a JSON list with rows of data and a JSON object. My goal is to iterate through the list and assign the rows to different objects within the JSON structure.

The first and last elements in the list are empty, followed by names and an indefinite number of "date" and "vote" pairs (refer to pastebin for clarity).

My objective is to aggregate all the votes under a specific name from the list into that particular JSON object.

How can I achieve this using JavaScript? Do I need to modify the JSON structure?

This is the initial JSON structure:

{
    "subjects": [
        {
            "electrical_and_electronic_engineering": {
                "grades": []
            }
        },

        {
            "italian_language_and_literature": {
                "grades": []
            }
        },

        {
            "english_language": {
                "grades": []
            }
        },

        {
            "mathematics_and_mathematical_complements": {
                "grades": []
            }
        },

        {
            "motor_and_sports_sciences": {
                "grades": []
            }
        },

        {
            "automatic_systems": {
                "grades": []
            }
        },

        {
            "history": {
                "grades": []
            }
        },

        {
            "technologies_and_design_of_electric_and_electronic_systems": {
                "grades": []
            }
        }
]
}

And here's the corresponding array:

[ '',
  'electrical and electronic engineering',
  '10',
  '7½',
  '8½',
  '5',
  '9',
  '7',
  '4',
  '7-',
  '7+',
  '6',
  '7½',
  'italian language and literature',
  '6½',
  '5+',
  '6',
  '7+',
  '5',
  '6½',
  'english language',
  '6+',
  '7',
  '7-',
  '7½',
  '7',
  '7+',
  'mathematics and mathematical complements',
  '4½',
  '9½',
  '7',
  '6½',
  '9',
  '7½',
  '4',
  '9',
  '7½',
  '7',
  '8',
  '8',
  'motor and sports sciences',
  '5',
  '7',
  '6',
  '9',
  '7',
  '10',
  '8',
  '10',
  '7',
  'automatic systems',
  '8',
  '8½',
  '10',
  '10',
  '8½',
  '9½',
  '10',
  '10',
  '10',
  '9-',
  'history',
  '4',
  '6',
  '5½',
  'technologies and design of electric and electronic systems',
  's',
  '7-',
  '7',
  '8',
  '8-',
  '7+',
  '7½',
  '6',
  '6',
  '8',
  '6+',
  '7-',
  '7-',
  '6',
  '7',
  '6',
  '8½',
  '' ]

Answer №1

Your array is a bit complex to work with. Here is a workaround to achieve what you are looking for. Keep in mind that a materia needs to be more than 2 characters long and the vote should be less than 3 characters, otherwise, it may not function correctly.

var array = [ '',
  'elettrotecnica ed elettronica',
  '10',
  '7½',
  '8½',
  '5',
  '9',
  '7',
  '4',
  '7-',
  '7+',
  '6',
  '7½',
  'lingua e letteratura italiana',
  '6½',
  '5+',
  '6',
  '7+',
  '5',
  '6½',
  'lingua inglese',
  '6+',
  '7',
  '7-',
  '7½',
  '7',
  '7+',
  'matematica e complementi di matematica',
  '4½',
  '9½',
  '7',
  '6½',
  '9',
  '7½',
  '4',
  '9',
  '7½',
  '7',
  '8',
  '8',
  'scienze motorie e sportive',
  '5',
  '7',
  '6',
  '9',
  '7',
  '10',
  '8',
  '10',
  '7',
  'sistemi automatici',
  '8',
  '8½',
  '10',
  '10',
  '8½',
  '9½',
  '10',
  '10',
  '10',
  '9-',
  'storia',
  '4',
  '6',
  '5½',
  'tecnologie e progettazione di sistemi elettrici ed elettronici',
  's',
  '7-',
  '7',
  '8',
  '8-',
  '7+',
  '7½',
  '6',
  '6',
  '8',
  '6+',
  '7-',
  '7-',
  '6',
  '7',
  '6',
  '8½',
  '' ];

var jsonObj = {'materie':[]}
var i = -1;
var currentKey = '';
array.map(function(val){
  if (val.length > 0) {
    if (val.length > 2) {
      currentKey = val.replace(/\s/g,'_');
      var newObj = {};
      newObj[currentKey] = {voti:[]}
      jsonObj['materie'].push(newObj);
      i++;
    } else {
      jsonObj['materie'][i][currentKey]['voti'].push(val);
    }
  }
});

document.write(JSON.stringify(jsonObj));

Answer №2

If my understanding is correct, you simply wish to extract names and votes from an array and insert them into a JavaScript object (JSON object). One approach to achieve this is by iterating over the array and checking if the format is consistent with name+date,vote. If the first item in the array is a character, it signifies a name. Then, you can locate the corresponding object in the JSON array and proceed to iterate through all values until another character item is encountered. Below is a quick solution, which may need adjustments for proper loop functionality:

//function to check for numbers
function isNumber(n) {
   return !isNaN(parseFloat(n)) && isFinite(n);
}   
function isEmpty(str) {
   return (!str || str.length === 0);
}
var jsonObject //the object we're appending the values to in your example
var name
var i = 1 //skipping the first empty value
for( i < voteArray.length() ){
  //check if a number 
  if (!isNumber(voteArray[i].charAt(0)) )
    if ( isEmpty(voteArray[i])){
      //end of list, break.
      break;
    }
    name = voteArray[i];
    //parse next two values and validate if they are numbers
    for( i < voteArray.length()){
        if(isNumber(voteArray[i+1]) && isNumber(voteArray[i+2])){
            //add the next numbers to JSON

            jsonObject[name].votes = //calculate total votes
            jsonOBject[name].date = //append date
            i=i+2 //increment i
        }
        else{
          if(isNumber(voteArray[i]){
            i = i+1;
            break;
          }else (isNumber(voteArray[i]){
            i = i+2;
            break;
          }
        }
    }
}

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

Exploring the world of CouchDB through jQuery and AJAX POST requests while navigating

I am in the process of building a simple web application. Today, I installed Couch 1.3.1 and set up a database. I am currently trying to save a document to my local Couch (localhost:5984) using a POST request from a client browser that is also on localhost ...

Converting XML data into a flat array format

I am facing a seemingly simple problem that I am currently unable to solve. Here is a formatted XML string that I have: <?xml version="1.0" encoding="utf-8"?> <e5Notification xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceS ...

Integrating jQuery Tooltip with Mouseover Event

I'm currently involved in creating a map of MIT projects for an architectural firm, and facing the challenge of maintaining the red dots mouseover state even when the mouse hovers over the tooltips that appear. Presently, the mouseover effect turns of ...

Employing an assortment of Box2Dbodies to generate numerous instances of the identical Body at various intervals

I'm currently working on my first game using libgdx, and I'm struggling with how to effectively use arrays within the context of libgdx/box2d. My goal is to create a series of box2dbodies that are identical but spawn at different times to increas ...

The React Material-UI Slider does not move when OnChangeCommitted is triggered

Struggling with implementing the Material UI slider in React, I encountered an issue where the OnChange function would trigger every time the value changed. I needed it to activate only when the left mouse button was released. Fortunately, I discovered a s ...

Trouble with Bootstrap 3's nav-justified feature not displaying correctly upon window expansion

Looking at this Bootstrap example page, I noticed a small issue with the nav-justified navigation. When the window is minimized, it transitions correctly to a mobile version. However, when the window is maximized again, the buttons remain in the mobile for ...

Tips for replacing div content using $.ajax similar to $.postWould you like to learn how

The Challenge: I need assistance in converting my existing code from using $.post to utilizing $.ajax for better synchronization and displaying a message until the request is completed. I am particularly interested in learning how I can achieve this usin ...

Optimizing Shader Caching in WebGL: Best Practices

I am currently in the process of developing a WebGL application, and I have encountered some challenges with shader storage... In most examples, shaders are directly written in plaintext within the xHTML file itself. However, this approach can lead to clu ...

Convert price to Indonesian Rupiah currency format with the help of Vue.js

Can someone help me convert the price format from IDR 50,000.00 to IDR 50.000 using JavaScript and Vue? I found a script on this website, but I am having trouble understanding how it works. The script looks like this: replace(/(\d)(?=(\d{3})+(?: ...

I aim to design a unique child window specifically for an "about" section within an electron js application on the Windows platform

I am looking to create a child browser window to showcase some key points about my application. According to the Electron JS documentation, it supports the "about" role for Mac OS but does not have built-in support for Windows. Therefore, I am in the pro ...

parallelLimit asynchronously executes in limited quantities once

Utilizing async.parallelLimit to update database records in batches of 10 that total 1000 each time is my current challenge. I am exploring how to implement this feature in my code but have run into some issues. Despite studying example interpretations, my ...

Warning: Unhandled promise rejection occurred while running the test

Currently delving into the world of selenium with a focus on testing the registration page. I've crafted a registration page class equipped with methods for monitoring registrations. However, upon attempting to execute a test within the application cl ...

Unpacking a collection in Xamarin using SQLite

I am currently facing an issue with storing a list in my Xamarin Forms App. I have successfully converted the JSON to C# using json2csharp for the ticket model. Additionally, I included the TextBlob to avoid getting an error message from SQLite stating tha ...

Incorporate a new attribute into objects within a designated level of a tree structure in

I am working with an array of objects structured as a tree. I have a requirement to add a new property called "dateType" to the objects at the 3rd level. let tree = [ { id: 1, name: "parent1", children: [ { id: 2, ...

Can all anchor tags properties on a website be simultaneously changed?

Recently, I discovered that using target="_blank" in anchor tags can leave a website vulnerable to security risks, and the recommended alternative is to use rel="noopener". In my current web project, all anchor tags are currently utilizing the target attri ...

Transform JQ map objects into an array based on a specified condition

After receiving the following input data: [ { "attributes": { "created": "2021-10-18T12:02:39+00:00", "enabled": true, "expires": null, "notBefore": null }, & ...

Utilize an A-frame feature to dynamically enable or disable a component through a

I have set up a virtual environment using A-frame () with some raining effects and a button. What I want to achieve is to have a function executed when the button is clicked, that function should remove the rain component from the scene. Here is the code s ...

PHP generating JSON array containing multiple arrays (data retrieved from MySQL)

I've been struggling to find a solution for this issue... Here is my code, the part causing trouble is how to create one large array from each SQL row: (the commented-out line is where the error occurs). $result = mysqli_query($con, "SELECT * FROM ` ...

Displaying a notification for a multi-selection using JavaScript

I need help with a piece of Html code I have. It's a list of countries, and what I want is to show an alert when one or more countries are selected to display which ones were chosen. I'm working with JavaScript only and don't want to use Jqu ...

Retrieve information from deeply nested JSON and showcase using Vue-Multiselect

My goal is to fetch data from the server and present it in Multiselect using nested JSON, which can be done through Vue-Multiselect. Once displayed, I should have the ability to add new tags as needed, essentially updating the data. While I can display o ...