Guide on retrieving a nested JSON array to extract a comprehensive list of values from every parameter within every object

A JSON file with various data points is available:

{
  "success": true,
  "dataPoints": [{
    "count_id": 4,
    "avg_temperature": 2817,
    "startTime": "00:00:00",
    "endTime": "00:19:59.999"
   }, 
   ...

I am trying to extract all the values of 'avg_temperature' from this JSON object.

getHistoryData() {
    this.historyDataService.getHistoryData(this.payload)
      .subscribe((data : any) => this.response = data.dataPoints[0].avg_temperature)
  }

Currently, I am able to capture only one value of 'avg_temperature'. However, I need a way to loop through the response and retrieve all the 'avg_temperature' values. Additionally, I want to save other parameters like 'startTime', 'endTime' in an array for future use.

Answer №1

If you need to utilize Array.map, that's the function you want to use.

By using the map() method, a new array is generated by applying a given function to each element of the original array.

To implement this in your code, follow this example:

fetchData() {
    this.dataService.getResults()
      .subscribe((result : any) =>
    this.updatedData = result.info.map(item => item.value)
}

Answer №2

You have the option to utilize map

let info ={"success":true,"dataPoints":[{"count_id":4,"avg_temperature":2817,"startTime":"00:00:00","endTime":"00:19:59.999"},{"count_id":4,"avg_temperature":2814,"startTime":"00:59:59.997","endTime":"01:19:59.996"},{"count_id":4,"avg_temperature":2816,"startTime":"00:39:59.998","endTime":"00:59:59.997"},{"count_id":4,"avg_temperature":2825,"startTime":"02:19:59.993","endTime":"02:39:59.992"},{"count_id":4,"avg_temperature":2828,"startTime":"02:39:59.992","endTime":"02:59:59.991"},{"count_id":4,"avg_temperature":2832,"startTime":"02:59:59.991","endTime":"03:19:59.99"},{"count_id":4,"avg_temperature":2841,"startTime":"03:39:59.989","endTime":"03:59:59.988"},{"count_id":4,"avg_temperature":2816,"startTime":"01:39:59.995","endTime":"01:59:59.994"},{"count_id":5,"avg_temperature":2668,"startTime":"04:19:59.987","endTime":"04:39:59.986"},{"count_id":3,"avg_temperature":2711,"startTime":"05:19:59.984","endTime":"05:39:59.983"},{"count_id":9,"avg_temperature":2697,"startTime":"03:59:59.988","endTime":"04:19:59.987"},{"count_id":4,"avg_temperature":2560,"startTime":"05:59:59.982","endTime":"06:19:59.981"},{"count_id":4,"avg_temperature":2837,"startTime":"03:19:59.99","endTime":"03:39:59.989"}]}

let output = info.dataPoints.map( ({avg_temperature}) => avg_temperature )

console.log(output)

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

Harness the Power of Generics in TypeScript for Automatic Type Inference

function execute<T>(operation1: (input: T) => void, operation2: (input: { key: string }) => T): void {} execute((params) => {}, () => 23); // The params here can be correctly inferred as number execute((params) => {}, (arg) => 23) ...

Issue encountered while deploying CandyMachinev2 on the development network due to a failure in executing commands

I have been grappling with a particular issue for the last day, and unfortunately, I have hit a roadblock. I have been attempting to adhere to the instructions on uploading a CMV2 to Devnet, following this guide: The code snippet I have been trying to uti ...

Enhance the <div> with interactive content through dynamic updates on click within the same element

I am currently developing an Editor-Menu for a website administration. When I open admin.php, the Editor-Menu should be loaded into the #ausgabe div using the code $('#ausgabe').load('./admin-ajax/ajax2.php'). This functionality is work ...

Implementing optimal techniques to create a JavaScript file for data retrieval in a Node.js application

I've developed a file specifically for data access purposes, where I'm keeping all my functions: const sql = require('mssql'); async function getUsers(config) { try { let pool = await sql.connect(conf ...

Establishing the parameters for a list that is not empty using a specific data type

Is it feasible to establish a non-empty list within TypeScript's type system? While I am aware that it is possible to define a list with a specific number of elements, similar to a Tuple: type TwoElementList = [number, number]; This approach is limi ...

What is the best way to include documentation for custom components using jsDoc?

Within my Vuejs inline template components, we typically register the component in a javascript file and define its template in html. An example of such a component is shown below: Vue.component('compare-benefits', { data() { // By return ...

Transfer the chosen language from the uib-dropdown language selector to the $scope variable

Here is a HTML template that allows the user to select a language: <div class="btn-group" uib-dropdown> <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" uib-dropdown-toggle> ...

Retrieve the XML document and substitute any occurrences of ampersands "&" with the word "and" within it

The XML file is not being read by the browser due to the presence of ampersands represented as "&". To resolve this, I am looking to retrieve the XML file and replace all instances of "&" with "and". Is this achievable? Despite attempting to use t ...

When the required attribute in Angular2 is conditional and the value is empty, the field will be adorned with the ng-valid class

In my current project using Angular 2.3.1, I have incorporated the following HTML element into a component template: <input class="form-control" type="text" id="password" name="password" placeholder="Password" [attr.required]="requirePasswd ? true : n ...

Executing JavaScript code from an external HTML file

My goal is to create and utilize native web components by defining them as HTML files containing markup, CSS, and Javascript all bundled together in one file, similar to how Vue handles .vue files. These components would be fetched from an external compone ...

Monitoring individual elements of an array within an Angular service

Is there a way to monitor changes in an array element within a service? Let's consider the following scenario with CartController and ProductListService. Within the ProductListService, data is fetched as follows: /** * Fetch all the products in us ...

Showing outcomes by making rapid consecutive AJAX requests

If you need a visual representation, I have a PHP script for a Hotel Management application that showcases a calendar (with columns representing days of the month and rows displaying prices per day). This script can be accessed in edit mode, where it gene ...

How can I retrieve x-data from an external file using Alpine.js?

I recently started exploring Alpine.js and grasped the fundamentals, but I'm facing challenges when trying to move functions outside of inline script tags. Consider this snippet from index.html: <div x-data="{ loading: false }"/> &l ...

Show data based on the chosen destination

Recently, I've been working on creating a simple printer manager to monitor the status of all my printers. Although I have successfully displayed all the data, I'm facing an issue while trying to organize it by location. The error message I keep ...

Why do I keep encountering the error "global is not defined" when using Angular with amazon-cognito-identity-js?

To start, run these commands in the command line: ng new sandbox cd .\sandbox\ ng serve Now, navigate to http://localhost:4200/. The application should be up and running. npm install --save amazon-cognito-identity-js In the file \src&bso ...

"What is the best way to ensure that a random array value is printed accurately within an If/Else statement in my Text Adventure

I am currently developing a text-based adventure game where the output in the console log is determined by specific input. The goal is for a message to appear if a goblin inflicts enough attack damage to reduce the player's defense to below 0, stating ...

Revive the JavaScript library for handling mouse wheel events

Utilizing the wheel-indicator JavaScript library, I am looking to revert the mouse wheel event back to its original state after it was initially set to preventDefault(). Despite attempting to use indicator.setOptions({preventMouse:"false"}) as suggested b ...

Add the hue value from Hue into the Chromajs HSL state value

My objective is to dynamically change the background color of a div based on user input. I plan to assign the user's input as the value of the state key hue, and then set another state key called color to hold the HSL representation of the hue using C ...

Transforming a list of arrays into a dictionary array

Here is some data that needs to be transformed {"array": [[1288.1639933233453], [1255.1777295971826], [1250.1075681742996], [1283.9962801780075], [1297.4411412000093]]} I am looking to change the format of the data as shown below [{"value": 1288.163993 ...

Modifying the row background in a DataTables drawCallback

Is there a way to dynamically change the background color of a row based on a specific value in a cell using drawCallback? $(table_id).DataTable({ //... "drawCallback": function (settings) { // Here, if the type of data in a particular ce ...