Determine the total count of a specific object within an array and organize the results

I recently retrieved JSON data from the firebug console and I am trying to calculate the total number of occurrences for the item "Open" in order to group the results by Team. This data is being extracted from our SharePoint list.

"d":
{
    "results":
    [
        {
            "__metadata":
            {
                "id": "Web/Lists(guid'1234578785596655')/Items(53)",
                "uri": "https://spteamsite.com/_api/web/lists/GetByTitle('Teams')/Items(53)",
                "etag": ""18"",
            "type": "SP.Data.TasksListItem"
        },
            "Team": "Team A",
            "taskStatus": "Open"
},
{
                "__metadata":
{
    "id": "Web/Lists(guid'1234578785596655')/Items(54)",
    "uri": "https://spteamsite.com/_api/web/lists/GetByTitle('Teams')/Items(54)",
    "etag": ""97"",
    "type": "SP.Data.TasksListItem"
},
                "Team": "Team B",
                "taskStatus": "Open"
},
{
    "__metadata":
    {
        "id": "Web/Lists(guid'1234578785596655')/Items(82)",
        "uri": "https://spteamsite.com/_api/web/lists/GetByTitle('Teams')/Items(82)",
        "etag": ""65"",
        "type": "SP.Data.TasksListItem"
    },
    "Team": "Team B",
    "taskStatus": "Open"
},
{
                "__metadata":
{
    "id": "Web/Lists(guid'1234578785596655')/Items(97)",
    "uri": "https://spteamsite.com/_api/web/lists/GetByTitle('Teams')/Items(97)",
    "etag": ""18"",
    "type": "SP.Data.TasksListItem"
},
                "Team": "Team C",
                "taskStatus": "Open"
},
{
    "__metadata":
    {
        "id": "Web/Lists(guid'1234578785596655')/Items(99)",
        "uri": "https://spteamsite.com/_api/web/lists/GetByTitle('Teams')/Items(99)",
        "etag": ""8"",
        "type": "SP.Data.TasksListItem"
    },
    "Team": "Team E",
    "taskStatus": "Open"
},
{
                "__metadata":
{
    "id": "Web/Lists(guid'1234578785596655')/Items(106)",
    "uri": "https://spteamsite.com/_api/web/lists/GetByTitle('Teams')/Items(106)",
    "etag": ""44"",
    "type": "SP.Data.TasksListItem"
},
                "Team": "Team D",
                "taskStatus": "Open"
},

After implementing my JavaScript code, I realized that I am not getting the correct count. The value returned is only 3, whereas it should be 300 or even more based on the data set. Here is a snippet of my JSON data for reference.

// JavaScript source code
$.ajax({
    url: _spPageContextInfo.webServerRelativeUrl + "/_api/web/lists/GetByTitle('Teams')/Items?$filter=taskStatus eq 'Open'&$select=Team,taskStatus",
    type: "GET",
    dataType: "json",
    async: "true",
    headers: {
        "accept": "application/json;odata=verbose",
    },
    success: function (data) {
        var dataArray = [];
        var countArray = [];
        var results = data.d.results;
        for (var i = 0; i < results.length; i++){
            for (key in results[i]) {
                if (results[i].hasOwnProperty(key)) {
                    countArray.push(results[i][key]);             
                }
            }
        }
        for (var i = 0; i < results.length; i++){
            var team = Object.keys(results[1]).length; //This is returning only the value of 3

            console.log(team);
        }
        console.log(countArray);
    },
    error: function(err) {
        alert(JSON.stringify(err));
    }
});

If you can provide some guidance on how to resolve this issue, it would be greatly appreciated.

I have made adjustments to the original JSON data as requested to ensure accuracy.

Answer №1

When you execute console.log(team), it will always display 3 because the statement Object.keys(results[1]).length calculates the number of properties (keys) in the first result object from the provided JSON data.

{
    "__metadata":
    {
        "id": "Web/Lists(guid'1234578785596655')/Items(53)",
        "uri": "https://spteamsite.com/_api/web/lists/GetByTitle('Teams')/Items(53)",
        "etag": "18",
        "type": "SP.Data.TasksListItem"
    },
    "Team": "Team A",
    "taskStatus": "Open"
}

You can group the results by iterating over them with a simple loop:

var results = data.d.results;
var openCount = results.length;
var groupedResults = {};

//Total number of open tasks
console.log(openCount);

for (var i = 0; i < openCount; i++) {
    var team = results[i]["Team"]

    if (!groupedResults[team]) {
        groupedResults[team] = [];
    }

    groupedResults[team].push(results[i]);
}

//Open tasks grouped by team
console.log(groupedResults);

//Count of open tasks for "Team B"
console.log(groupedResults["Team B"].length);

Below is the code snippet demonstrating the functionality based on the sample data provided:

var data = {
    "d":
    {
        "results":
        [
            {
                "__metadata":
                {
                    "id": "Web/Lists(guid'1234578785596655')/Items(53)",
                    "uri": "https://spteamsite.com/_api/web/lists/GetByTitle('Teams')/Items(53)",
                    "etag": "18",
                    "type": "SP.Data.TasksListItem"
                },
                "Team": "Team A",
                "taskStatus": "Open"
            },
            {
                "__metadata":
                {
                    "id": "Web/Lists(guid'1234578785596655')/Items(54)",
                    "uri": "https://spteamsite.com/_api/web/lists/GetByTitle('Teams')/Items(54)",
                    "etag": "97",
                    "type": "SP.Data.TasksListItem"
                },
                "Team": "Team B",
                "taskStatus": "Open"
            },
            {
                "__metadata":
                {
                    "id": "Web/Lists(guid'1234578785596655')/Items(82)",
                    "uri": "https://spteamsite.com/_api/web/lists/GetByTitle('Teams')/Items(82)",
                    "etag": "65",
                    "type": "SP.Data.TasksListItem"
                },
                "Team": "Team B",
                "taskStatus": "Open"
            },
            {
                "__metadata":
                {
                    "id": "Web/Lists(guid'1234578785596655')/Items(97)",
                    "uri": "https://spteamsite.com/_api/web/lists/GetByTitle('Teams')/Items(97)",
                    "etag": "18",
                    "type": "SP.Data.TasksListItem"
                },
                "Team": "Team C",
                "taskStatus": "Open"
            },
            {
                "__metadata":
                {
                    "id": "Web/Lists(guid'1234578785596655')/Items(99)",
                    "uri": "https://spteamsite.com/_api/web/lists/GetByTitle('Teams')/Items(99)",
                    "etag": "8",
                    "type": "SP.Data.TasksListItem"
                },
                "Team": "Team E",
                "taskStatus": "Open"
            },
            {
                "__metadata":
                {
                    "id": "Web/Lists(guid'1234578785596655')/Items(106)",
                    "uri": "https://spteamsite.com/_api/web/lists/GetByTitle('Teams')/Items(106)",
                    "etag": "44",
                    "type": "SP.Data.TasksListItem"
                },
                "Team": "Team D",
                "taskStatus": "Open"
            }
        ]
    }
};

function printResult(value) {
  var d = document.createElement('div');
  
  d.innerHTML = JSON.stringify(value);
  document.body.appendChild(d);
  console.log(value);
}

var results = data.d.results;
var openCount = results.length;
var groupedResults = {};

//Total number of open tasks
printResult("Open tasks for all teams: " + openCount);

for (var i = 0; i < openCount; i++) {
    var team = results[i]["Team"]
    
if (!groupedResults[team]) {
        groupedResults[team] = [];
    }
    
    groupedResults[team].push(results[i]);
}

//Open tasks grouped by team
printResult(groupedResults);

//Count of open tasks for "Team B"
printResult("Open tasks for Team B: " + groupedResults["Team B"].length);
div {
  border: 1px solid black;
  margin: 10px;
}

Answer №2

From my understanding of your query, you are looking to group the information by Team and then calculate the total sum of open items. With the help of linq.js, achieving this becomes simple.

var groupedData = Enumerable.From(data).GroupBy("$.Team", null,function (key, group) {
                 return {
                   Team: key,
                   OpenTotal: group.Sum("$.Open")                     
                 }
    }).ToArray();

Modified Version

var result = Enumerable.From(jsonObject)
    .GroupBy(
        "$.City",
        null,
        "{ City: $, TotalCount: $$.Count() }").ToArray()

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

Node.js encountered an error: Module 'mongoose' not found

C:\Users\Alexa\Desktop\musicapp\Bots\Soul Bot>node bot.js Node.js Error: Missing module 'mongoose' at Function._resolveFilename (module.js:334:11) at Function._load (module.js:279:25) at Module.requir ...

Storing data in MongoDB using JavaScript on a web platform

Imagine a straightforward website with a common structure <html> <head></head> <body> <script type="text/javascript"> </script> </body> </html> Can data be written to MongoDB fr ...

Combine two arrays of objects and merge properties using the Ramda library

I have two arrays as shown below: ['TAG.u', 'TAG.c'] and the other one is: [{name:'some',key:'TAG.u'}, {name:'some new', key: 'TAG.b'}, {name:'some another' , key:'TAG.c'} ...

The issue with the jQuery Mobile onclick event is that it fails to remove the ui-disabled

Ever since I delved into coding with jQuery Mobile, I've noticed a change in the function that once effortlessly removed the "ui-disabled" class. Now, all it does is display an alert message... Snippet from the HTML code: <div data-role="navbar ...

Attaching events to the window in Vue.js

Having recently started working with Vue.js, I have come across a problem related to attaching and detaching keyboard events to the window within one of my components. Below are the methods I am using: created() { this.initHotkeys(); }, beforeDestroy() ...

Challenges with VueJS Routing and Navigation

Encountering challenges with VueJS during my first attempt at using it The majority of my page template is stored in the index.html file located in the root directory I have implemented 3 components, each containing the main content body for different &a ...

Tips on creating a dropdown list in HTML with the previous year's worth of data

Currently, I am facing an issue with a dropdown list on my web application. The requirement is to display the last 12 months in proper order within the dropdown list. To clarify, let's say it is February 2016, the dropdown list should start from March ...

What is the best way to initiate an animation once the one before it has finished?

I am facing an issue with my animation function where all animations play simultaneously. This is not the desired behavior; I would like to play each animation after the previous one ends. Can someone guide me on how to achieve this? canvas = document.get ...

Distributing your React component on npm

I've been working on a React component for over a week now and I'm struggling to publish it on NPM. The lack of credible resources online has made this process challenging for me. Can anyone offer step-by-step guidance or recommend reliable reso ...

Tips on obtaining the JSON format of an object containing an array variable

In my class, I have three variables including an array. I created a method specifically for use with json_encode(). public function getJSONString(){ return [ 'id' => $this->id, 'name' => $this->name, ...

Cancelling an ongoing AWS S3 upload with Angular 2/Javascript on button click

I'm currently working with Angular 2 and I have successfully implemented an S3 upload feature using the AWS S3 SDK in JavaScript. However, I am now facing a challenge: how can I cancel the upload if a user clicks on a button? I've attempted the ...

Utilize Jq in Shell script to analyze and identify differing values between two JSON files and display the unmatched data

Is there a way to extract the objects from one JSON file that do not have a match in another JSON file? For example, JSON file1: [ { "name": "ABC", "age": "23", "address": "xyz" }, { &qu ...

java JSON responses containing long values that have been rounded

Upon receiving a JSON response from my RESTful service developed in Java, I have noticed that long data type values ending with 01 are being rounded down to 00. Allow me to provide examples: For instance, 12345123459876501 is returned as 1234512345987650 ...

Encountering a php error when decoding multiple JSON files due to an unexpected end of file

Hey there! I'm currently working on a project where I need to load JSON files from a specific folder and then decode them to populate a database. Below is the code snippet I am using for this task: <?php $con = mysqli_connect("localhost", "root", ...

Server not recognizing nested routes in React-Router

I am currently using Express.js to render a React application on the server side, but I have encountered an issue where some of my routes are getting skipped over unexpectedly. Here is my server.js: app.get('*', (req, res) => { conso ...

What is causing my basic angularjs to not function properly?

In my angularjs test instance, I am using a global variable but the alert tag is not functioning as expected. This code snippet is from my first example on codeschool. Any thoughts on why the alert is not running? <!DOCTYPE html> <html xmlns="ht ...

Node.JS - Struggling to successfully export environment variables between scripts in package.json

Currently, I am working on a Node.JS project using Express and I am facing an issue while setting up environment variables to differentiate between development and production environments. I have created a shell script file containing some environment vari ...

Utilizing only JavaScript to parse JSON data

I couldn't find a similar question that was detailed enough. Currently, I have an ajax call that accesses a php page and receives the response: echo json_encode($cUrl_c->temp_results); This response looks something like this: {"key":"value", "k ...

Trouble Arising from Making a POST Request to Spotify's API

I am currently developing a web application that allows users to search the Spotify Library, add songs to playlists, and then save those playlists to their Spotify Accounts. Almost everything is functioning correctly except for the saving of playlists thro ...

Issue with Jade not displaying external JSON data

I am struggling with a jade template that is supposed to display all possible solutions from the QPX Express search request: { kind: 'qpxExpress#tripsSearch', trips: { kind: 'qpxexpress#tripOptions', requestId: 'RwDOf6H ...