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

Having trouble getting Tinymce to appear on the screen

I am currently attempting to install TinyMCE for use with my text editor in order to provide the user with a text box similar to the one on Stack Overflow. However, I am encountering an issue where it is not displaying as expected. In the header of my ind ...

Switching between three div elements along with two icons can be done by using toggle functionality

Is there a way to make the icon change back when clicked again without making major changes to the existing code? Looking for suggestions on how to achieve this functionality. function myFunction() { var element = document.getElementById("demo"); el ...

What benefits does utilizing a liquid template in Azure Logic Apps offer when it comes to transforming XML data?

Converting XML to JSON in logic apps is as easy as calling json(xmlStringHere), so it begs the question: why would we need a liquid template? ...

Can Vue instances support private computed properties?

Vue is a versatile tool that I utilize for both service classes and components. When it comes to reactive computeds, they prove to be incredibly beneficial. However, I often find myself wanting a clear way to differentiate between public interface compute ...

Experiencing difficulties in installing opensea-js using NPM

While working on my project, I encountered an issue when trying to install opensea-js as a dependency. My Node version is v14.16.0 and NPM version is v7.7.5. Every time I run the command npm install --save opensea-js, it results in an error. I attempted c ...

Troubleshooting CodeIgniter's AJAX call functionality issue

I have been attempting to test AJAX functionality within CodeIgniter, but unfortunately, I haven't had any success so far. Can someone please point out where I might be making a mistake? Below is my test_page.php: <!DOCTYPE html> <head> ...

Protect a one-page application using Spring's security features

After successfully developing a single page application using JavaScript, I incorporated a few jQuery commands and Twitter Bootstrap for added functionality. The method used to load my page is demonstrated below: $('#contact').click(function () ...

Setting up ESLint and Prettier for Accurate Error Detection in TypeScript and Next.js Development

As I work with TypeScript and Next.js, I decided to implement strict code formatting rules by adding the following configuration to my eslintrc.json file: "rules": { "prettier/prettier": "error" } However, when I ran npm ru ...

Issue: Module 'stylelint' not found in Angular Project

I've been attempting to execute this command to validate all of the .scss files (and even tried with .css files) and I keep encountering this error. $ stylelint "apps/**/*.scss" It worked once before but not anymore, even after restarting my compute ...

Guidelines on incorporating emotion/styled into React applications with TypeScript

Including my root component in the ThemeProvider from @emotion/react has granted me access to props.theme. Here is an example: const StyledDiv = styled.div` background-color: ${(props) => props.theme.palette.primary.main}; `; Issue: TypeScript indica ...

Strategies for retrieving the latest content from a CMS while utilizing getStaticProps

After fetching blog content from the CMS within getStaticProps, I noticed that updates made to the blog in the CMS are not reflected because getStaticProps only fetches data during build time. Is there a way to update the data without rebuilding? I typica ...

React search filter feature with dropdown selection

After successfully implementing a search filter in my React app, I encountered an issue when trying to incorporate a select tag to change the search filter criteria. class BookList extends Component { state = { search: '', selectedValue: ' ...

Warning: Using synchronous XMLHttpRequest on the main thread is no longer recommended as it can negatively impact the user's experience

I encountered an issue with my project while attempting an Ajax request [Warning] Using synchronous XMLHttpRequest on the main thread is now considered deprecated due to its negative impact on user experience. function retrieveReviews() { var reviewsD ...

Blending Angular5 and AngularJS in Polymer

We are considering launching two new projects - one using Angular 5 and the other utilizing Polymer. The second project is intended to serve as a component library for reuse in not only the Angular 5 project but also in other AngularJS projects. After res ...

Cannot work on repl.it; it seems to be incompatible with the freeCodeCamp - JavaScript Algorithms and Data Structures Projects: Roman Numeral Converter

Recently completed my Roman Numeral Converter and it functions correctly on repl.it. However, when testing it on freecodecamp, the output displayed: // running tests convertToRoman(2) should return "II". convertToRoman(3) should return "III". ... // tests ...

Gather information from various entities using JavaScript

I am looking to parse data from an Object and save them in an array. Specifically, I aim to extract all the US shoe sizes and compile them into an array. However, when utilizing the filter method, it only retrieves the first item with the "us" value. { ...

Passing NextJS props as undefined can lead to unexpected behavior and

Struggling with dynamically passing props to output different photo galleries on various pages. One of the three props works fine, while the others are undefined and trigger a warning about an array with more than one element being passed to a title elemen ...

JavaScript heap exhausted while running Docker container

Typically, I start my application by running npm run dev. The package.json file contains a script like the one below: "scripts": { "dev": "nodemon server.ts", } Everything is working fine in this setup. I have cr ...

Node.js refusing to acknowledge the get request handler for the homepage of the website

My Node.js server setup is quite simple: const express = require('express'); const app = express(); const http = require("http"); const path = require('path'); const favicon = require('serve-favicon'); // Public fil ...

React frontend encountered a connectivity issue while trying to establish a network connection

Our app utilizes next.js connected to express, which is further linked to AWS MySql for database management. While attempting to load some products stored in the database, an error message pops up: TypeError: NetworkError when trying to fetch resource. ...