retrieve a collection of objects using JavaScript

Consider the following array:

var booksStudents = [
  {
   name: "David", 
   books: {
      "fantasy": 23,
      "action": 31,
      "thriller" 21,
      }
   },
   name: "Paul", 
   books: {
      "fantasy": 17,
      "action": 13,
      "thriller" 23,
      }
   },
   name: "Zoe", 
   books: {
      "fantasy": 5,
      "action": 7,
      "thriller" 28,
      }
}];

I am trying to create an array of objects with each person's name and the total number of books they have. While I am familiar with using reduce on simple arrays, I am struggling with this array of objects. I considered using .map and .reduce, but so far I haven't found a suitable solution.

Answer №1

studentsBooks = studentsBooks.map(function(record){
  var total = 0;
  for(var category in record.books){
    total += record.books[category];
  }
  record.totalCount = total;
  return record;
})

Utilize the map function along with a for..in loop to calculate the total count.

Answer №2

Initially, there are a few errors in the array of objects that you provided. Allow me to highlight them for you.

var booksStudents = [
  {
   name: "David", 
   books: {
      "fantasy": 23,
      "action": 31,
      "thriller": 21,  // : missing
      }
   },
   {                   // { missing
   name: "Paul", 
   books: {
      "fantasy": 17,
      "action": 13,
      "thriller": 23, // : missing
      }
   },
   {                  // { missing
   name: "Zoe", 
   books: {
      "fantasy": 5,
      "action": 7,
      "thriller": 28, // : missing
      }
}];

After fixing these mistakes, you can achieve your desired result by using the following code snippet.

var newArray = [];
$.each(booksStudents,function(index,value){
    var currObj = {};
    currObj.name= this.name;
    currObj.totalBooks = parseInt(this.books.fantasy) +parseInt(this.books.action)+parseInt(this.books.thriller) ;
   newArray.push(currObj);
});

console.log(newArray);

Feel free to check out this working Fiddle; look at the console for the output.

The output is displayed as shown below.

https://i.sstatic.net/KFe52.png

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

Having trouble updating a MongoDB array through a RESTful API PUT request

I'm brand new to the MEAN stack and recently completed a tutorial. I've been working on enhancing a simple application that utilizes a RESTful API to update a MongoDB. Currently, I'm using a PUT statement to modify specific parts of my colle ...

What methods can be used to reveal the URL or string hidden by the current "Search" button?

I am a beginner with no coding experience. Please forgive me if my question sounds silly. I am interested in learning how to "discover" the correct string to add to an existing internal-domain-url (even though I am not the admin of that domain) in order t ...

Ensuring strictNullChecks in Typescript is crucial when passing values between functions

When using the --strictNullChecks flag in TypeScript, there seems to be an issue with inferring that an optional property is not undefined when the check occurs in a separate function. (Please refer to the example provided, as articulating this clearly is ...

Flipping Y and X axis coordinates within an HTML5 canvas

I'm currently working with an interface that includes an HTML5 canvas, and I'm facing a challenging task of inverting the X and Y coordinates when a position is selected. My initial approach was to subtract the width of the canvas from the select ...

Is there a way to modify the express function I created to take in an array as its parameter and reuse it effectively?

I have developed a function that retrieves a JSON object of an Order by finding details based on the Id provided. Below is the code and model for reference. I am looking to enhance this function to also accept an array of ids and return the combined JSON o ...

Converting a lengthy HTML document into numerous JPEGs (or any preferred image format)

I am working on a lengthy webpage that can be viewed as having 40 individual pages. Each "page" is separated by a horizontal rule () and has a fixed height of 860px. My goal is to convert each of these "pages" into JPG images automatically. Can anyone pr ...

The canvas doesn't seem to be rotating even after executing the setTransform

Within my HTML5 canvas, I have been experimenting with drawing lines and rotating them around the center point. My goal is to reset the canvas's transformation each time I draw, followed by re-translating/rotating the canvas. However, I have encounter ...

What is the most efficient way to condense a UUID to 15 characters or fewer while also expanding it?

How can a UUID (v4) without dashes be shortened to a string of 15 characters or less? It should also be possible to revert back to the original UUID from the shortened string. The objective is to shorten it for inclusion in a flat file, where the field fo ...

What is the significance of using parentheses around a function in JavaScript?

Currently, I am developing an application using Java and JavaScript, and while reviewing some code today, I came across a segment that seemed confusing to me. var myVariable = (function(configObj){ var width = configObj.width; var height = config ...

Extracting a compilation of video content from a YouTube channel through JSON data retrieval

I'm struggling to display the 5 most recent videos (title, updated, thumbnail (hqDefault)) from a specific channel using JSON data. I've tried various guides but can't seem to parse it correctly. Any suggestions on how to achieve this? I&apo ...

Sending an array via an AJAX POST request using jQuery

I'm having trouble with my POST function not passing the data[] array. Can someone confirm if my array is correct? Or perhaps there's something missing in my POST function? function doAction(prefix) { if ($('#' + prefix + '_actio ...

"What could be the reason behind the sudden disappearance of the TinyMCE icon in my Vue

Welcome to my unique website design! https://i.sstatic.net/rtEwF.png Check out the special tinymce code I created https://i.sstatic.net/8su0i.png https://i.sstatic.net/9y2AO.png ...

Steps for integrating a login system in an Angular application using an existing REST API backend

My buddy and I are collaborating on an app - he's handling the backend (Node.js) while I'm working on the frontend. He set up sessions on his end and gave me the URL that I need to use for logging in. It's a POST request like this: http:// ...

Find the most recent date in a file and display the line associated with it

I am working with a document named Application.txt that consists of multiple columns and rows as shown below: ApplNo DocsURL DocDate 4782 www…. 7/28/2003 4782 www…. 11/23/2008 4782 www…. 3/24/2012 5010 www…. 4/5/2003 5010 ww ...

Updating the text of a Mat-Label dynamically without the need to reload the page

In my application, there is a mat-label that shows the Customer End Date. The end date is fetched initially through a GET request to an API. Let's say the end date is 16-05-2099, which is displayed as it is. There is also a delete button implemented f ...

capturing webpage content with javascript for use in a screenshot

Is there a way to capture a screenshot of a webpage using JavaScript and utilize the canvas tag for this purpose? I attempted to use the html2canvas plugin in the past, but found it lacking in power. I would like to achieve this without relying on extern ...

Utilizing React/Redux to perform individual fetch calls for specific routes

I have a Redux store that needs to be connected to my App, but I only want to fetch data relevant to the component currently rendered by react-router. Currently, it is connected to a container element (App.js) which passes all props to the router's c ...

"Transmit the document by utilizing the file ID in the form of

When sending a file from my server, I can easily define the path and it goes through successfully. However, with the node-telegram-bot-api, there is an option to send a document that is already hosted on telegram servers by providing the file_id in the doc ...

Tips for inserting a page break after every item in a loop in Visualforce when generating a PDF document

I need help with rendering a VF page as PDF. The VF page iterates over a list of account records using the repeat tag. I want to apply a page break for each element in the repeat tag. The code below is working, but it has an issue - it shows an empty PDF p ...

What is the best way to add a filter to a nested array?

I am currently facing a challenge in creating a multiple filter for multiple arrays without duplicating the nested array. I am working with vuejs and some plugins that are relying on the array, so my only option is to filter it without modifying it. Using ...