Retrieve information from jsonObject

Can anyone help me with counting the number of passes and fails for each subject in a JSON object array? Here is an example:

 [{"Subject":"Maths","status:"Pass"},{"Subject":"Maths","status:"Pass"},
     {"Subject":"Maths","status:"Fail"},{"Subject":"Maths","status:"Fail"},
    {"Subject":"English","status:"Pass"},{"Subject":"English","status:"Fail"}]

I am looking to transform this data into an object array that looks like this:

[{"Subject":"Maths","Pass":2,"Fail":2},"Subject":"English","Pass":1,"Fail":1}]

This information will be coming from an API and the subjects may vary. Any suggestions on how to handle this dynamic data?

Answer №1

In this code snippet, the reduce function is used along with an accumulator array to check if the 'Subject' exists. If it does not exist, a new object is created with the values of keys 'Subject', 'Pass', and 'Fail'. If the 'Subject' already exists, the values of 'Pass' and 'Fail' are updated accordingly.

let k = [{
    "Subject": "Maths",
    "status": "Pass"
  },
  {
    "Subject": "Maths",
    "status": "Pass"
  },
  {
    "Subject": "Maths",
    "status": "Fail"
  },
  {
    "Subject": "Maths",
    "status": "Fail"
  },
  {
    "Subject": "English",
    "status": "Fail"
  },
  {
    "Subject": "English",
    "status": "Pass"
  }
]

let res = k.reduce((acc, curr) => {
  let findSubjectIndex = acc.findIndex((item) => {
    return item.Subject === curr.Subject;
  })
  if (findSubjectIndex === -1) {
    let crtOb = Object.assign({}, {
      Subject: curr.Subject,
      Pass: curr.status === "Pass" ? 1 : 0,
      Fail: curr.status === "Fail" ? 1 : 0
    })
    acc.push(crtOb)

  } else {
    console.table(acc)
    acc[findSubjectIndex].Pass = acc[findSubjectIndex].Pass + (curr.status === "Pass" ? 1 : 0);
    acc[findSubjectIndex].Fail = acc[findSubjectIndex].Fail + (curr.status === "Fail" ? 1 : 0);
  }
  return acc;
}, []);
console.log(res)

Answer №2

Utilize Array.reduce and Object.values for efficient processing

let data = [{"Subject":"Maths","status":"Pass"},{"Subject":"Maths","status":"Pass"},
     {"Subject":"Maths","status":"Fail"},{"Subject":"Maths","status":"Fail"},
    {"Subject":"English","status":"Pass"},{"Subject":"English","status":"Fail"}];

// Generate an object with subject as key and values as desired objects
let processedData = Object.values(data.reduce((accumulator, {Subject, status}) => {
  // Check if subject exists in the object, update count accordingly
  if(accumulator[Subject]) accumulator[Subject][status] = (accumulator[Subject][status] || 0) + 1;
  // Add a new entry for the subject if it doesn't exist
  else accumulator[Subject] = {Subject, [status] : 1};
  return accumulator;
}, {}));
console.log(processedData);

Answer №3

Providing code that is more user-friendly and easy to grasp for beginners like myself

var jsonObject  = [{"Subject":"Maths","status":"Pass"},{"Subject":"Maths","status":"Pass"},
     {"Subject":"Maths","status":"Fail"},{"Subject":"Maths","status":"Fail"},
    {"Subject":"English","status":"Pass"},{"Subject":"English","status":"Fail"}];

var passMathCount = 0;
var failMathCount = 0;
var passEnglishCount= 0;
var failEnglishCount = 0;

//Loop through each object
for(var i = 0; i < jsonObject.length; i++) {
    
    var obj = jsonObject[i];
    //Determine status for different subjects
    if(obj.status == "Pass" && obj.Subject == "Maths")
      passMathCount++;
    else if(obj.status == "Fail" && obj.Subject == "Maths")
      failMathCount++;
    else if(obj.status == "Pass" && obj.Subject == "English")
      passEnglishCount++;
    else
      failEnglishCount++;
}

//Construct json object array
var jsonInstance = [{"Subject": "Maths", "pass": passMathCount, "fail":failMathCount},
                    {"Subject": "English", "pass": passEnglishCount, "fail":failEnglishCount}];
                    
console.log(jsonInstance);

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

Next.js | Error: Attempting to access a property of an undefined value (property name: 'secret')

I encountered an issue while trying to authenticate the API routes in next.js. The page level authentication is working properly, but when attempting to fetch the session in the API routes, I am facing an error. Error - TypeError: Cannot read properties of ...

An error is being thrown by SetState when included within componentDidmount

I am currently learning React JS and have started working on a small application using it. I'm encountering an issue with the SetState method inside the componentDidMount lifecycle method. The scenario is that I have a parent/home component, which ca ...

Exceeded request limit resulting in a timeout while making multiple AFNetworking requests

I'm having trouble with a piece of code that is supposed to download 40 JSON files. NSMutableArray *mutableOperations = [NSMutableArray array]; for (NSDictionary *dict in general_URL) { NSURL *url = [dict objectForKey:@"url"]; NS ...

Get the JS file by tapping the download button, and access the

In creating the web page, I utilize a modular approach. Leveraging node js and the node-static server are essential components of this process. One specific requirement I have is implementing file downloads from a computer to a device using a button trigg ...

Managing the invocation of a promise multiple times in AngularJS, and handling some specific exceptions

After previously asking a question on handling promises multiple times in AngularJS (AngularJS handle calling promise multiple times), I am facing a new challenge. This time, I need to retrieve a list of cities, but encounter an exception. Similar to how ...

javascript + react - managing state with a combination of different variable types

In my React application, I have this piece of code where the variable items is expected to be an array based on the interface. However, in the initial state, it is set as null because I need it to be initialized that way. I could have used ?Array in the i ...

How can I transform a JSON object into a series of nested form fields?

Can anyone suggest a reliable method for converting a JSON object to nested form fields? Let's consider the following JSON object: {'a':{'b':{'c':'1200'}}}, 'z':'foo', 'bar':{&apo ...

"Despite modifying the ID in the response data of Angular MongoDB, the request data ID remains unchanged

Having trouble with managing requests and responses, specifically when a customer tries to add multiple items of the same product but in different sizes. The initial step involves checking if the ID exists by using a count and an if statement. If it exists ...

Recording JavaScript Cookie Visit Counts and Tracking Last Login Dates

I am a beginner in JavaScript and cookies, and I am attempting to create a cookie that can show the number of times someone has visited a website, the date of their last visit, and the expiration date of the cookie. Initially, I tried modifying code from ...

Transferring information from the initiator to a pop-up window in Internet Explorer

I am looking to pass the scope and other values to a child window. It currently works as expected in Chrome, but not in Internet Explorer. Is there a workaround for this issue? var templateUrl = "/someviewpage"; var wOptions$ = 'menubar= ...

Display a string of text containing multiple interactive links

I have a table and I want to create an interactive effect where, upon mouseover or click of certain elements, text will appear next to it. This text may contain multiple lines and clickable links within the content. For instance, in the table generated by ...

My GraphQL Query is throwing a JSON error when using the curlopt_postfields option. What could be causing this

I'm having some trouble with my code and I keep encountering this error message. Any ideas on what might be causing this issue? I believe I've properly escaped all the quotations. {"errors":[{"message":"json body could ...

Decode Jackson - a process to extract and translate multiple base enums from

Can enums with a one-based index be deserialized successfully? enum Status { Active, Inactive } The value {status:1} should correspond to Status.Active, but Jackson is incorrectly mapping it to Status.Inactive. ...

Tips for Troubleshooting External Evaluation Scripts

For a specific example, take a look at the haystack.js script from How Big is Your Haystack? I've been searching for a solution and it seems that using the //# sourceURL=name.js comment is the way to go. However, I am struggling with the process of a ...

The challenge of loading multiple objects asynchronously in three.js

When I try to load multiple models onto the same scene simultaneously, only one model is successfully loaded. For instance, if I have a building scene with various objects like chairs and toys inside, only one object gets loaded when I try to load them all ...

Is it possible to customize the MongoDB Collection before loading the web application by fetching data asynchronously using Promises?

I am currently working with MongoDB and NodeJS, trying to preload my Collection customers every time the site is loaded. The process involves emptying the collection, populating it with empty Documents, and then replacing them with real data fetched from a ...

Determining if a URL links to an image when the file extension is not informative

I am currently working on building an AJAX call to retrieve data from an API with a messy data structure. The challenge I'm facing is that the array returned by each AJAX call can contain up to 30 elements, some of which have image URLs without a file ...

Guide on extracting information from a JSON array consisting of objects and adding it to a Pandas Dataframe

Working with Jupyter Notebook and handling a Batch API call that returns a JSON array of objects can be tricky. The parsing process involves using for loops, which may seem weird at first. In my case, I needed to extract specific JSON object information an ...

Successive promises linked together with varying parameters

Originally, I utilized callbacks for all of my nodejs functions that needed to access mysql or txt files. Unfortunately, this resulted in messy code with callbacks nested inside one another, so I decided to switch to promises. The question now is, how can ...

Searching through data fields in MongoDB that have been filled with information

In my Mongoose queries, I am dealing with models known as "Activities" that have a specific schema structure. This schema includes fields such as actor, recipient, timestamp, activity, event, and comment. var activitySchema = new mongoose.Schema({ act ...