Extract every value associated with a particular key using JSON

Is there a way to extract all of the "-temp" values from the provided JSON data?

{
  "weather":{
    "notes":{
      "cities":[
        {
          "-id":"scranton",
          "-temp":"17"
        },
        {
          "-id":"paris",
          "-temp":"16"
        },
        {
          "-id":"new york",
          "-temp":"18"
        }
      ]
    }
  }
}

I attempted to retrieve this information using JavaScript, but unfortunately it returned undefined

data.weather.notes.cities['-temp']

Can anyone suggest how I can effectively retrieve every value of "-temp" from this dataset?

Answer №1

If you want to extract temperature data from multiple cities, you can utilize the map method:

const temperatures = data.weather.notes.cities.map(city => city["-temp"]);

console.log(temperatures); // ["17", "16", "18"]

Alternatively, you can access each city's temperature individually like this:

const { cities } = data.weather.notes;

console.log(cities[0]["-temp"]); // "17"

You can also iterate through all cities and display their temperatures:

for (let city of cities) {
  console.log("Temperature in %s is %s°", 
    city["-id"], city["-temp"]
  );
}

Answer №2

One way to approach this problem is by looping through all the cities and extracting the temperature information.

data.weather.notes.cities.forEach(function(city) {
 for (var key in city) {
    if (key == "-temp")
    {
      console.log(city[key])
    }
 }
});

@ZER0's suggestion seems like the most effective solution.

Answer №3

let weatherData = {
  "conditions": {
    "cities": [
      {
        "-name":"tokyo",
        "-temp":"26"
      },
      {
        "-name":"london",
        "-temp":"15"
      },
      {
        "-name":"sydney",
        "-temp":"29"
      }
    ]
  }
};
  
for(let index in weatherData.conditions.cities) {
    let cityInfo = weatherData.conditions.cities[index];
    console.log(cityInfo["-temp"]); //Accessing temperature of each city
}

Answer №4

You won't be able to treat JSON in the same way as you do with jquery selectors. In this scenario, it is necessary to iterate through your array of cities.

const data = {
  "weather":{
    "notes":{
      "cities":[
        {
          "-id":"london",
          "-temp":"21"
        },
        {
          "-id":"tokyo",
          "-temp":"24"
        },
        {
          "-id":"sydney",
          "-temp":"19"
        }
      ]
    }
  }
};

const cityTemperatures = data.weather.notes.cities.map(city => city['-temp']);

//output: ["21", "24", "19"]

Refer to map documentation for more details.

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

Mastering the Art of SQL Submission with PHP Ajax Requests

I've encountered an issue with a form that, upon validation, triggers two Ajax requests before submitting the data to create an entry in a MySQL database. The Ajax requests generate URLs to Google Documents using upload.php. However, when certain unk ...

Angular's asynchronous HTTP request allows for non-blocking operations when

I'm currently working with Angular 6, and I've encountered an issue while updating my resource instance in the following way: this.user = api.getUser(); public getUser(): User { const myHeader = new HttpHeaders({ 'Authorization' ...

How to efficiently use nested $.each() in DataTables with jQuery

After receiving Json data from the server, I utilize DataTables to display the information accordingly. The json contains multidimensional arrays with rows consisting of columns that may have more than one value. Here's an excerpt: { "info_table ...

In both Chrome and Edge, the default value for the <select> tag is successfully set, however, this functionality is not working in

I have defined two values in the created method, 2018 and My Name, and assigned them to separate data properties. These data properties are then passed as v-bind to a component. The issue I am facing is that in Chrome and Edge, both values are set as defa ...

Can an HTML DIV be resized along with its contents?

Is it possible to scale a container with animated elements inside to fit the browser window, or do you have to adjust each child element individually? ...

AJAX File Upload: Sequentially Queuing Multiple Files

I am a beginner in the world of Javascript and jQuery. When I try to upload multiple files through a form, only the last file gets uploaded repeatedly. My goal is to upload each file one by one using AJAX requests asynchronously. Here's how I have ...

What is the method for incorporating a CSRF token into BootstrapTable when using the POST data method?

How can I include a CSRF token in bootstrapTable when using the POST method for data? I am working on a project and trying to add a CSRF token in bootstrapTable. There is some information about CSRF on bootstrap-table.com. Can anyone help me with this iss ...

Encountering a "Page Not Found" error while configuring Passport in Express 4

Struggling with integrating passport into my Node.js application. Despite rearranging my requirements in app.js, I'm unable to resolve the issue. The error message reads: Not Found 404 Error: Not Found at /home/salma/Desktop/my-project/app.js:5 ...

Discovering duplicate values in a JSON object using JavaScript (JQuery)

Below is a JSON object that contains information about various materials: [ { "idMaterial": "Alloy 450 (15Cr6Ni1.5Cu)_S45000", "tipoMaterial": "Alloy 450 (15Cr6Ni1.5Cu)", "uns": "S45000", "temperatura": "NL", "p ...

Guide on programmatically redirecting a user to a different route

I am currently working on a VueJS 3 application using Quasar, and I am facing difficulties with programmatically utilizing the Router. The issue can be summarized as follows: 1. The Challenge When attempting to navigate the User to a different route, onl ...

`Problem encountered when trying to present JSON content in an Android Gridview`

Encountering difficulties while attempting to showcase JSON data in a Gridview within an Android application using the Volley library through a URL. The error message received is: com.android.volley.NoConnectionError:java.io.IOException The JSON data i ...

Exploring the retrieval of JavaScript array elements from a ListModel within QML

Currently, I have some JavaScript data that consists of a list of objects containing other objects and arrays, which I want to append to a ListModel. This is what the structure looks like (assuming that the data is generated elsewhere and its structure sh ...

Node.js Express application: Managing endpoint conflicts

After searching for a solution to this issue and not finding one, I apologize if this question is repetitive. In my express+node.js application, I have two endpoints defined as follows: // Retrieves a tweet by unique id app.get('/tweets:id', fu ...

Display the title when the mouse hovers over

I am currently working on a minimalist portfolio site where I showcase various projects through images on the landing page. As I iterate over all the projects using {projects.map(({ id, title, route, src }, index) => ())}, I encountered an issue with di ...

Executing two select queries in PHP and transforming the results into JSON structure

Is there a way to retrieve two JSON objects using just one AJAX call in conjunction with a PHP function? This is an example of the HTML structure: // Bootstrap Modal <div id="paymentViewModal" class="modal fade"> <form method="POST" id=" ...

Could there be any issues with the structure of my mongoose schema?

I've been stuck for 3 hours trying to solve this problem. I can't seem to retrieve any data from my document. var mongoose = require('mongoose'); var Schema = mongoose.Schema; var accountSchema = mongoose.Schema({ username: String ...

Python Selenium : Struggling to locate element using ID "principal"

As part of my daily work, I am currently working on developing a Python Script that can automate the process of filling out forms on various websites. However, I encountered an issue with Selenium while trying to interact with certain types of webforms. F ...

Is there a built-in method called router.reload in vue-router?

Upon reviewing this pull request: The addition of a router.reload() method is proposed. This would enable reloading with the current path and triggering the data hook again. However, when attempting to execute the command below from a Vue component: th ...

Press the button in the parent component, retrieve information from the child component, and utilize it in a method (Vue 3)

I am currently using Vue3 in combination with Bootstrap 5. MY ISSUE: I am trying to click a button in my parent.vue. Upon clicking, I want to retrieve the data from my child.vue and access it within the method in my parent.vue. However, the data always r ...

Update text displayed on radio button selection using jQuery

Is there a way to change the label text on a selected radio button from "Set default" to just "default" using jQuery? I think I need to use the class radio-default as the selector, but I'm not very familiar with jQuery. <div class="radio-default ...