Leveraging the reduce method in processing JSON data

Here is the JSON data I have:

{
    "meta": {
        "totalPages": 13
    },
    "data": [{
        "type": "articles",
        "id": "3",
        "attributes": {
            "title": "AAAAA",
            "body": "BBBB",
            "created": "2011-06-22T14:56:29.00z",
            "updated": "2011-06-22T14:56:28.00z"
        }
    }],
    "links": {
        "self": "http://example.com/articles?page[number]=3&page[size]=1",
        "first": "http://example.com/articles?page[number]=1&page[size]=1",
        "prev": "http://example.com/articles?page[number]=2&page[size]=1",
        "next": "http://example.com/articles?page[number]=4&page[size]=1",
        "last": "http://example.com/articles?page[number]=1&page[size]=1"
    }
}

If this JSON response is from a web server, is there a possible way to utilize the reduce() method in this scenario?

I attempted the following approach:

$.ajax({
  url:"http://...",
  type: "GET",
  headers:{"application/vnd+json"},
  success: function(data){
  var result = data.cells.reduce(function(array, object) {
    return array.concat(object.type);
   }, {});

  console.log(result);
 }
)};

Is it feasible to apply reduce here? My goal is to implement the reduce function for the provided JSON structure. Do you see any issues with my AJAX implementation?

Answer №1

As an illustration, you have the option to utilize reduce() in order to compute the total number of data objects where type:"articles"

const response = {
    "meta": {
        "totalPages": 13
    },
    "data": [{
        "type": "articles",
        "id": "3",
        "attributes": {
            "title": "AAAAA",
            "body": "BBBB",
            "created": "2011-06-22T14:56:29.00z",
            "updated": "2011-06-22T14:56:28.00z"
        }
    },{
        "type": "articles",
        "id": "6",
        "attributes": {
            "title": "AAAAA",
            "body": "BBBB",
            "created": "2011-06-22T14:56:29.00z",
            "updated": "2011-06-22T14:56:28.00z"
        }
    },
    {
        "type": "articles",
        "id": "10",
        "attributes": {
            "title": "AAAAA",
            "body": "BBBB",
            "created": "2011-06-22T14:56:29.00z",
            "updated": "2011-06-22T14:56:28.00z"
        }
    }],
    "links": {
        "self": "http://example.com/articles?page[number]=3&page[size]=1",
        "first": "http://example.com/articles?page[number]=1&page[size]=1",
        "prev": "http://example.com/articles?page[number]=2&page[size]=1",
        "next": "http://example.com/articles?page[number]=4&page[size]=1",
        "last": "http://example.com/articles?page[number]=1&page[size]=1"
    }
}

const totalArticles = response.data.reduce((count, val)=>{
  if(val.type === 'articles') count++
  return count;
  }, 0)

console.log(`Total no. of articles : ${totalArticles}`); // Total no. of articles : 3

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 CSS files undergo modifications when executing the command "npm run dev"

I've been working on an open-source project where I encountered a bug. Even when there are no images to display, the "Load More" button in the web browser extension still appears. To fix this, I decided to add the class `removeButton` to the button an ...

What is the hierarchy for displaying elements depending on the props?

I have developed a search input component that includes an icon which I want to reposition (either on the left or right side) depending on different scenarios. This input is part of a bootstrap input-group, so modifying the order of elements within my di ...

Passing component properties using spaces in VueJS is a simple and effective

I am encountering an issue where I want to pass component props from my view, but I am facing a challenge due to the presence of a space in the value. This causes Vue to return the following error: vendor.js:695 [Vue warn]: Error compiling template: - inva ...

Rails inspired tag selection tool akin to Stack Overflow

In my Rails application, I am looking to implement a tagging system for models. I want to create a tag selection feature similar to Stack Overflow where I can type in a tag like 'rails' and a drop-down list of options containing that tag will app ...

HTML5 Positioning Timeout

While working on my project, I incorporated the HTML Geolocation feature. However, I have observed that it is not always dependable. I am looking for a solution to add a backup plan that will time out after x seconds and display an error message. Any sugg ...

Having difficulties in sending array data to the REST endpoint

Currently, I am utilizing Django REST framework within my project. One of the models in use has the following structure: class Post(models.Model): title = models.CharField(max_length=100, null=False) content = HTMLField() created_at ...

What could be causing the issue of the title in req.body to display as 'undefined'?

I am currently learning about NODE JS and practicing working with POST forms from PUG to a NODE JS server. I am facing an issue where the submission input is coming back as 'undefined' when I submit a form from the web browser. In the code snipp ...

Ensuring React's setupProxy functions properly in conjunction with express.js

I've encountered an issue while trying to pass images from express to react. My express.static is correctly set up, so when I visit localhost:5000/public/images/me.jpeg, the image loads in my browser. However, when I attempt to use <img src="/publi ...

What is the process of fetching the selector value through AJAX and storing it in PHP?

I am working with the prop() method in jQuery and I need to extract the value "show_pdf1" in PHP, save it for processing before returning the final result from readPdf.php. How can I achieve this using only the property method without any additional method ...

Arrange objects in an array based on certain criteria using JavaScript in a dynamic

I have an array containing various items that need to be sorted according to specific rules. The goal is to group all values with "rules" together, and ensure that "ELIG_DATABASE" is grouped with "ELIG_SERVICE." const items =[{"name":"ELIG_ ...

Creating a Modal Dialog with Justified Tab and Dropdown Using Bootstrap 4.1

I am struggling with Bootstrap 4.1 as I try to align content to the right side. Specifically, I have a Navigation Bar that triggers a Modal Dialog containing Tabs. The dropdown menu on the far right of the Tab is what I want to justify to the right. Here a ...

Special characters like greater/less than signs have not been properly encoded

I am currently facing an issue in regards to escaping strings on the server side (using Node.js & Express.js) that contain greater/less than signs (<, >). Below is the code snippet I'm using on the server side: socket.on('message', fu ...

Turning an Array of Objects into a typical JavaScript Object

Below are arrays of numbers: var stats = [ [0, 200,400], [100, 300,900],[220, 400,1000],[300, 500,1500],[400, 800,1700],[600, 1200,1800],[800, 1600,3000] ]; I am seeking guidance on how to transform it into the JavaScript object format shown below. ...

I'm confused as to why I am only receiving one object entry in my fetch response instead of the expected list of entries

Is there a way to fetch all entries as a response instead of just one value? For example, when the next value returned by the fetch is {"next":"/heretagium"}, I can replace "/hustengium" with "heretagium" to get th ...

Ensure that the jQuery Knob is set to submit any modifications only after the final adjustment

Utilizing jQuery Knob by anthonyterrien, I have configured the step to be 20. My goal is to transmit the knob's value to the server. The issue arises when the change function is triggered every time the user adjusts the knob using either a right or le ...

Obtain the final array within an array composed of multiple arrays

My dilemma involves working with a dynamically generated array, where I need to extract only the values from the last array for aggregation purposes, discarding all others. Imagine a structure similar to this: let target = [] let data = [ [ { name: &apo ...

Creating a javascript variable in c#

Currently, I am working on incorporating the selected index text from a DropDownList into a JavaScript string. My approach involves storing the text in a hidden field and retrieving it through C# to ensure the JavaScript variable retains its value even aft ...

Error in Email Attachment - Invalid Attachment File Path

My workflow is as follows: User selects a local file while filling out an HTML form AJAX sends the form data to my ASMX Public classes use JSON data to create an email (with the file being an attachment) While there are many ...

The async function in Jasmine is causing issues with expectedAsync functionality

Currently conducting the following examination: it("should receive rejection", async done => { class someTest { async run(){ return this.rejectFunc(); } async rejectFunc(){ return new Promise( ...

Pass data dynamically to router in ExpressJS

Within my app.js file, there are several variables defined: var user = "max"; Additionally, there is a route function set up like so: app.post('/register', user.postRegister); In the /routes/user.js file, there is a module function structured ...