Selecting a specific JSON object to generate numerous arrays

Within my JSON array are thirty objects representing the last 30 days, including today. Each object contains specific properties:

{
    "date": "2013-05-20",
    "notCachedRequestsDevelopment": "115482",
    "cachedRequestsDevelopment": "4732914",
    "notCachedBandwidthDevelopment": "15525231867",
    "cachedBandwidthDevelopment": "2571078929",
    "rejectRequestsDevelopment": "44068",
    "rejectBandwidthDevelopment": "23169212",
    "nonCSSCachedRequestsDevelopment": "6789",
    "nonCSSNotCachedRequestsDevelopment": "1440",
    "notCachedRequestsProduction": "9",
    "cachedRequestsProduction": "1089270",
    "notCachedBandwidthProduction": "2186497",
    "cachedBandwidthProduction": "616508357",
    "rejectRequestsProduction": "359",
    "rejectBandwidthProduction": "168977",
    "nonCSSCachedRequestsProduction": "0",
    "CDNCachedRequests": 6062986,
    "CDNNotCachedRequests": "272901.0",
    "CDNRejectRequests": "84764.0",
    "CDNAllBandwidth": 56006050473.574,
    "billingBandwidth": 22525362831.36,
    "billingHits": 6489103
}

My goal is to create new Arrays based on this JSON data. For instance:

I require a new array named totalBandwidth that sums up the following properties from each JSON object:

notCachedBandwidthDevelopment + cachedBandwidthDevelopment + rejectBandwidthDevelopment + notCachedBandwidthProduction + cachedBandwidthProduction + rejectBandwidthProduction

Another array, developmentBandwidth, should calculate the total by adding these values from each object:

cachedBandwidthDevelopment + notCachedBandwidthDevelopment

… and so forth.

While I can accomplish this task using a for loop for each new array, I am curious if there is a more efficient method to achieve the same result?

Answer №1

Option 1: Utilizing Array.prototype.map()

Experience the new javascript Array.prototype.map() array function. In this scenario, consider using:

var developmentBandwidth = origArray.map(function(obj) {
  return parseInt(obj.cachedBandwidthDevelopment) + parseInt(obj.notCachedBandwidthDevelopment);
});

developmentBandwidth will result in an array of numbers.

Please be aware that this functionality is exclusively available in ECMAScript 5 and modern browsers. For more details, refer to MDN at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

If you need compatibility with older browsers, MDN offers a compatibility function for your convenience.


Option 2: Leveraging jQuery.map()

It appears that the jQuery library offers a similar feature. You can achieve the same result as shown above with:

var developmentBandwidth = $.map(origArray, function(obj, index) {
  return parseInt(obj.cachedBandwidthDevelopment) + parseInt(obj.notCachedBandwidthDevelopment);
});

For a detailed comparison between the two options, click here

Answer №2

If you want to streamline the elimination of duplicates even more, consider this coffeescript approach which uses concise variable names for improved readability:

demoFunction = (daysdata) ->
  result = {}
  totalsNeeded = {foo: ['a', 'b'], bar: ['b','c']}
  sumFields = (fields, obj) ->
    sum = (t,s) -> t+obj[s]
    fields.reduce(sum,0)
  buildDaysArray = (fields) ->
    sumFields(fields,data) for data in daysData
  for name, fields of totalsNeeded
    result[name] = buildDaysArray(fields)
  result


day1 = {a: 1, b: 2, c: 3}
day2 = {a: 4, b: 5, c: 6}
alert(JSON.stringify(demoFunction([day1, day2]))) # => {"foo":[3,9],"bar":[5,11]}

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

Numerous SVGs sharing identical IDs

Is it possible to include multiple SVGs on an HTML page and utilize the same IDs in each of them? <div> <svg height="0" width="0"> <clipPath id="svgPath"> ........ </svg> <svg height="0" width="0"> < ...

Guide on exporting type definitions and utilizing them with npm link for a local package

I am in the process of developing a new testing tool called tepper as an alternative to supertest. My goal is to make this package available in both ESM and CJS formats. However, I'm encountering an issue where users of the library are unable to locat ...

Apologies, the system encountered an issue while trying to access the "name" property which was undefined. Fortunately, after refreshing the page, the error was successfully resolved

When the profile route is accessed, the code below is executed: import React, { useState, useEffect } from 'react' import { Row, Col, Form, Button } from 'react-bootstrap' import { useDispatch, useSelector } from 'react-redux' ...

What is the best way to retain selection while clicking on another item using jQuery?

There is a specific issue I am facing with text selection on the page. When I apply this code snippet, the selected text does not get de-selected even after clicking .container: jQuery('.container').on("mousedown", function(){ jQuery('. ...

Discover the magic of using the spread operator to effortlessly insert key-value pairs into an object!

Currently, I am grappling with the challenge of handling variable products using the spread function. For instance, in an online store selling clothes (similar to the screenshot linked below), I am looking to track when a user adds different sizes of the s ...

Effective steps after Ajax request

Whenever a user clicks the "like" button, I perform a check in the database to see if they have already liked the photo. This check is done using ajax. If the photo has already been liked, the success message will indicate "already liked", otherwise it wi ...

Guide to fetching a string using Angular's http client?

I am facing an issue with calling a server that returns a csv file as text. I am using Angular's HttpClient and I need to prevent it from trying to cast the csv file to JSON. I tried setting the responseType to 'text' in the httpOptions, but ...

Issue with RESTClient not displaying the Response Message from the Server

Currently, I am tackling a ruby project that involves utilizing RESTClient to interact with an API. The API is returning a 400 HTTP Status Code for a specific outcome along with a corresponding response message in JSON format. However, upon inspecting the ...

including a content tag into an input field within a template

I'm experimenting with the new html5 template tag to create a versatile form that can be used in various situations without relying heavily on javascript. Check out this fiddle to see what I have so far http://jsfiddle.net/684uH/ My objective is to ...

The issue of AngularJS directive failing to update controller variable

After conducting an extensive search on both Google and Stack Overflow, I was unable to find a solution to the issue at hand. So, moving forward, here is the problem I am facing: I have created a directive that is intended to retrieve data selected in a ...

Delete ObjectId from Array using Node and Mongoose

Currently, I am working on a website that features a comments section for campsites. This platform is similar to Yelp but focuses on reviewing campsites. Each campsite in the MongoDB collection has a field called "comments" which stores the IDs of all comm ...

Encountering a connectivity issue with the MongoDB server

While I wrote my server IP on the mongoose connection string, I am unable to insert data into MongoDB. How can I resolve this issue? var express = require("express"); var app = express(); var mongoose = require('mongoose'); mongoose.connect(&ap ...

Utilizing conditional statements within the array.forEach method to select specific sub-objects within an array of objects

Need help troubleshooting an if statement inside a function that is called by a forEach array loop. My array contains objects, with each object structured like this: arrofobj = [ {"thing_id":"1a", "val": 1, "Type": "Switch","ValType":{"0":"Open","1":" ...

How can I convert an HTML table into a PDF using TCPDF while ensuring that all content is contained within a single div in PHP?

I have successfully converted my JSON API data into an HTML TABLE format and now I am trying to generate a PDF from this HTML TABLE using TCPDF in PHP. Despite trying various methods related to PDF generation using TCPDF, I am facing issues with my code wh ...

Using Regular Expressions in Javascript

I have gone through numerous posts with this title, but so far, none of them have addressed my specific query... My requirement is to utilize regex in the following format: "/^ user provided input $/i". The user can include the special regex character * e ...

Having trouble with Vuejs Ternary Operator or Conditional in v-bind-style?

Having some unexpected issues while trying to implement a style conditional for items in Vuejs. I have come across Stack Overflow posts on how to use a ternary, either through an interpolated string or a computed style object. I've attempted both met ...

Is there a way to set up an automatic pop-up for this?

Experience this code function AutoPopup() { setTimeout(function () { document.getElementById('ac-wrapper').style.display = "block"; }, 5000); } #ac-wrapper { position: fixed; top: 0; left: 0; width: 100%; height: 100%; back ...

What is the reason behind the absence of a removeRange() method in CopyOnWriteArrayList?

What is the reason behind having the removeRange method in the ArrayList but not in its concurrent sibling? The protected void removeRange(int fromIndex, toIndex) method. I was just curious about this discrepancy, although it's not essential and I ...

The presence of decimal values within an AJAX URL

Struggling to pass decimal values in an AJAX request to a server-side endpoint. Everything runs smoothly except when trying to include a decimal value in the URL. The "." character is recognized as reserved within the URL schema, causing a 404 error. Seeki ...

What could be the underlying reason for the unusual behavior observed in this range polyfill implementation?

I am attempting to transform an HTML5 range input into a set of radio buttons. Each radio button corresponds to a value within the original range, with text displaying its value. However, I am encountering an issue where the last piece of text, meant to sh ...