Guide to forming a JavaScript array from nested JSON data

Looking to parse through an array of objects related to London weather data from the OpenWeatherMap API.

How can I create three distinct arrays in JavaScript, each with variable names "dtArray", "tempMinArray", and "tempMaxArray", containing only values for "dt", "temp_min", and "temp_max" respectively in the following format:

dtArray = [firstvalue, secondvalue, thirdvalue, ...]
tempMinArray = [firstvalue, secondvalue, thirdvalue, ...]
tempMaxArray = [firstvalue, secondvalue, thirdvalue, ...]

Should I utilize a loop, or is there another method like map or each that would be more efficient?

My current attempt:


var tempMinArray = new Array;
for (i = 0; i < results.data.length; i++) {
    tempMinArray = results.data.list[i].main.temp_min;
}

Answer №1

To achieve this, you can utilize the Array#map method.

$.get('https://api.openweathermap.org/data/2.5/forecast?q=london&appid=7ce3e1102e1902e0f878c2a640e95aed')
  .then(function(resp) {
    var dts = resp.list.map(item => item.dt);
    var tempMins = resp.list.map(item => item.main.temp_min);
    var tempMaxs = resp.list.map(item => item.main.temp_max);
    
    console.log('dt:', dts);
    console.log('temp_min:', tempMins);
    console.log('temp_max:', tempMaxs);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Answer №2

Methods for achieving :

  • Utilize the Single Array filter() method and iterate over the objects within an array for all three different arrays using ES6 syntax.

    EXAMPLE

var jsonObj = {
"list": [{
"dt": 1522227600,
"main": {
"temp": 278.73,
"temp_min": 278.73,
"temp_max": 278.941,
"pressure": 1006.02,
"sea_level": 1013.69,
"grnd_level": 1006.02,
"humidity": 100,
"temp_kf": -0.21
}
}, {
"dt": 1522238400,
"main": {
"temp": 279.1,
"temp_min": 279.1,
"temp_max": 279.234,
"pressure": 1004.6,
"sea_level": 1012.13,
"grnd_level": 1004.6,
"humidity": 100,
"temp_kf": -0.14
}
}, {
"dt": 1522249200,
"main": {
"temp": 278.83,
"temp_min": 278.83,
"temp_max": 278.898,
"pressure": 1005.72,
"sea_level": 1013.37,
"grnd_level": 1005.72,
"humidity": 99,
"temp_kf": -0.07
}
}]
};

let dtArray = [];
let tempMinArray = [];
let tempMaxArray = [];

jsonObj.list.filter(obj => {
   (obj.dt) ? dtArray.push(obj.dt) : '';
   (obj.main.temp_min) ? tempMinArray.push(obj.main.temp_min) : '';
   (obj.main.temp_max) ? tempMaxArray.push(obj.main.temp_max) : '';
});

console.log(dtArray);
console.log(tempMinArray);
console.log(tempMaxArray);

  • Implement Separate Array map() method for each array as suggested by 31piy.

    EXAMPLE

var jsonObj = {
"list": [{
"dt": 1522227600,
"main": {
"temp": 278.73,
"temp_min": 278.73,
"temp_max": 278.941,
"pressure": 1006.02,
"sea_level": 1013.69,
"grnd_level": 1006.02,
"humidity": 100,
"temp_kf": -0.21
}
}, {
"dt": 1522238400,
"main": {
"temp": 279.1,
"temp_min": 279.1,
"temp_max": 279.234,
"pressure": 1004.6,
"sea_level": 1012.13,
"grnd_level": 1004.6,
"humidity": 100,
"temp_kf": -0.14
}
}, {
"dt": 1522249200,
"main": {
"temp": 278.83,
"temp_min": 278.83,
"temp_max": 278.898,
"pressure": 1005.72,
"sea_level": 1013.37,
"grnd_level": 1005.72,
"humidity": 99,
"temp_kf": -0.07
}
}]
};

var dtArray = jsonObj.list.map(obj => obj.dt);
var tempMinArray = jsonObj.list.map(obj => obj.main.temp_min);
var tempMaxArray = jsonObj.list.map(obj => obj.main.temp_max);

console.log(dtArray);
console.log(tempMinArray);
console.log(tempMaxArray);

  • Utilize JavaScript for ... in loop to iterate through the array of objects.

    EXAMPLE

var jsonObj = {
"list": [{
"dt": 1522227600,
"main": {
"temp": 278.73,
"temp_min": 278.73,
"temp_max": 278.941,
"pressure": 1006.02,
"sea_level": 1013.69,
"grnd_level": 1006.02,
"humidity": 100,
"temp_kf": -0.21
}
}, {
"dt": 1522238400,
"main": {
"temp": 279.1,
"temp_min": 279.1,
"temp_max": 279.234,
"pressure": 1004.6,
"sea_level": 1012.13,
"grnd_level": 1004.6,
"humidity": 100,
"temp_kf": -0.14
}
}, {
"dt": 1522249200,
"main": {
"temp": 278.83,
"temp_min": 278.83,
"temp_max": 278.898,
"pressure": 1005.72,
"sea_level": 1013.37,
"grnd_level": 1005.72,
"humidity": 99,
"temp_kf": -0.07
}
}]
};

var dtArray = [];
var tempMinArray = [];
var tempMaxArray = [];

for (var i in jsonObj.list) {
  dtArray.push(jsonObj.list[i].dt);
  tempMinArray.push(jsonObj.list[i].main.temp_min);
  tempMaxArray.push(jsonObj.list[i].main.temp_max);
}

console.log(dtArray);
console.log(tempMinArray);
console.log(tempMaxArray);

Answer №3

$.get("https://api.openweathermap.org/data/2.5/forecast?q=london&appid=7ce3e1102e1902e0f878c2a640e95aed", function(data, r){
  var dArray = data.list.map(item => item.dt)
  var tempMinArray = data.list.map(item => item.main.temp_min)
  var tempMaxArray = data.list.map(item => item.main.temp_max)
  console.log(dArray, tempMinArray, tempMaxArray)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

Retrieving POST data from AngularJS AJAX in Python FlaskExplanation: In this

Utilizing Angular's AJAX call, I am sending data to my Flask backend for natural language processing. Here is the AJAX code snippet: $scope.processText = function(){ $http({ method: "POST", url: "http://127.0.0.1:5000/processTex ...

Issue with pop-up functionality on web page using HTML, CSS, and JavaScript

Recently, I created a unique popup using HTML. You can see the complete code (excluding CSS) here: https://codepen.io/nope99675/pen/BawrdBX. Below is the snippet of the HTML: <!DOCTYPE html> <html> <head> <meta charset=&quo ...

What is the best way to enable autocomplete in AngularJS?

I am working with an object that contains both a name and an ID. I want to implement autocomplete functionality based on the name property. Below is the code snippet that I have tried: //Js file var app=angular.module("myapp",[]); app.controller("controll ...

optimal application of css with jquery

I have a question about using jQuery to set the padding of a class or id. I am able to successfully change the height of an element with this code: $('.menu').css({ height: '90px' }); But now, I need to apply a specific CSS rule in jQ ...

Reload the webpage locally without sending a request to the server

My goal is to refresh the browser window without needing to hit the server. I am considering using javascript for this task. Below is the code that I have, but I'm not entirely clear on what it does! <body onload="JavaScript:AutoRefresh(5000);"> ...

A guide on managing Ngb Bootstrap carousel slide with a button in Angular

I encountered a situation like this: I need to implement a Ngb Bootstrap carousel with buttons for Previous and Next to control the slide images. Clicking on the Previous button should display the previous slide image, and clicking on the Next button shou ...

A visually stunning image showcase with dynamic resizing and strategically placed white spaces using the m

I'm attempting to create a responsive image gallery using the Masonry jQuery plugin, but despite reading numerous articles and forum posts on the topic, I can't seem to get it to work properly. The gallery is displaying many blank spaces. My app ...

How come an element retrieved with getElementById in Next.js comes back as null despite the presence of a defined document?

Having trouble using SSR in my React/Next app. Despite having the document present (and being able to visually see the div with the id plTable), the getElementById function is returning null. I even tried calling getElementById after 6 seconds to ensure ...

Retrieve the value of [routerLinkActive] in the component's class

Recently, I've been working on a tab component called TabComponent and it includes the following HTML template: <a [routerLink]='link' [routerLinkActive]="[is-active]">link label</a> <button>Close tab</button> The c ...

Is there a way for me to create a route similar to Instagram's setup, such as localhost:3000

I am looking to structure my routes similar to Instagram (instagram.com/username). Currently, I have implemented the following route: router.get('/:name', loggedin, function (req, res, next) { res.render('profile', {"Request name" ...

How come I am unable to determine the size of the element using this pointer trick?

When working with arrays in the C programming language, it is important to understand how memory is allocated and accessed. int arr[]= {1,2,3,4,5}; In this example, our system uses 4 bytes to store integer data. As a result, the memory address of each el ...

What is the method or variable called "afterShow" used for in FancyBox V4 and how does it differ from its counterpart in JQuery-FancyBox V3?

We previously utilized the V3 edition of Fancybox, incorporating our increaseImageClicks and increaseVideoClicks functions within its afterShow function: /* FANCYBOX OLD (https://web.archive.org/web/20210325170940/https://fancyapps.com/fancybox/3/docs/): * ...

What is the reason for having two plugin declarations within the galleriffic.js file?

I am currently working on enhancing the functionality of galleriffic.js by implementing a feature that will update a <div> element with text content as images are being changed. However, I am facing some challenges understanding the code. What perpl ...

Using AngularJS to Retrieve a Specific DOM Element Using its Unique Identifier

Example Please take a look at this Plunkr example. Requirement I am looking for a way to retrieve an element by its id. The provided code should be capable of applying a CSS class to any existing DOM element within the current view. This functionality ...

What could be causing my dropdown links to malfunction on the desktop version?

I've been developing a responsive website and encountering an issue. In desktop view, the icon on the far right (known as "dropdown-btn") is supposed to activate a dropdown menu with contact links. However, for some unknown reason, the links are not f ...

Is it possible in Java to convert a JSONObject to a JSONStringer and vice versa?

I'm feeling a bit puzzled about how to navigate through the apparent limitations of the JSONStringer class. I am aware that JSONStringer is designed to link together JSON rather than create it as a whole, but when a function only returns a JSONStringe ...

Adjust padding of elements based on scrolling movements

Currently, I am attempting to adjust the padding of a specific element based on how far down the page the user scrolls. Ideally, as the user scrolls further down the page, the padding will increase, and as they scroll back up, the padding will decrease. H ...

Ways to eliminate double slashes from URL in Next Js. Techniques for intercepting and editing a request on the server side using getServerSideProps

Looking to manipulate a server-side request - how can this be accomplished? http://localhost//example///author/admin/// The desired output is: http://localhost/example/author/admin/ In Next Js, how can duplicate slashes in a URL be eliminated and req ...

Tips for transforming a Vue 2 website into a progressive web application (PWA) were requested

As I explored the PWA functionality in Vue 3, I noticed that it is not available in Vue 2. If anyone has any insights on how to successfully convert a Vue 2 project into a PWA, I would greatly appreciate your input. Thank you! ...

Updating object values within a while loop using JavaScript

I am facing an issue with managing an array of JavaScript objects that have a property 'table' with values table1, table2, table3, or table4. Each table should only accommodate 6 members. I have implemented a while loop to check if 'table1&a ...