What is the best way to notify the JSON code below using jQuery?

I have received a JSON response after using the Reverse Geocoding API from Google. The response includes various address components such as route, sublocality, locality, and political information.

{
"results": [
    {
        "address_components": [
            {
                "long_name": "Goth Haji Umed Ali Gabole-Konker Road",
                "short_name": "Goth Haji Umed Ali Gabole-Konker Rd",
                "types": [
                    "route"
                ]
            },
            {
                "long_name": "Haji Umaid Ali Goth",
                "short_name": "Haji Umaid Ali Goth",
                "types": [
                    "political",
                    "sublocality",
                    "sublocality_level_2"
                ]
            },
            {
                "long_name": "Gadap",
                "short_name": "Gadap",
                "types": [
                    "political",
                    "sublocality",
                    "sublocality_level_1"
                ]
            },
            {
                "long_name": "Karachi",
                "short_name": "Karachi",
                "types": [
                    "locality",
                    "political"
                ]
            }
                ],
      "status": "OK"}

Below is the code snippet:

function successFunction(position) {
        var lat = position.coords.latitude;
        var lng = position.coords.longitude;
        var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&key=AIzaSyBcV_CkYu5VvJb1ZZF8GWCAMyZhEDgpYzk";
        jQuery.get(url, function (result)
        {
            console.log(result);
        }
        );
    }

The JSON response can be viewed in the console. I am looking to extract the city name "Karachi". How can I achieve this?

Answer №1

Give this a try:

Let's take a look at the following JavaScript code snippet that filters an address component based on the city name 'Karachi':

var jsonObj = {
"results": [{
"address_components": [{
"long_name": "Goth Haji Umed Ali Gabole-Konker Road",
"short_name": "Goth Haji Umed Ali Gabole-Konker Rd",
"types": [
"route"
]
},
{
"long_name": "Haji Umaid Ali Goth",
"short_name": "Haji Umaid Ali Goth",
"types": [
"political",
"sublocality",
"sublocality_level_2"
]
},
{
"long_name": "Gadap",
"short_name": "Gadap",
"types": [
"political",
"sublocality",
"sublocality_level_1"
]
},
{
"long_name": "Karachi",
"short_name": "Karachi",
"types": [
"locality",
"political"
]
}
],
"status": "OK"
}]
};

var res = jsonObj.results[0].address_components.filter(obj => obj.long_name == 'Karachi');

console.log(res[0].long_name);

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

Bringing Together AngularJS and JQuery: Using $(document).ready(function()) in Harmony with Angular Controller

Can you lend me a hand in understanding this? I have an angular controller that is structured like so: angular.module('myApp', []) .controller('ListCtrl', function($scope, $timeout, $http){ // Making API calls for Health List ...

Clicking will cause my background content to blur

Is there a way to implement a menu button that, when clicked, reveals a menu with blurred content in the background? And when clicked again, the content returns to normal? Here's the current HTML structure: <div class="menu"> <div class=" ...

JavaScript Nested Array Looping Script

I am currently working on a loop script for my application that checks for the full capacity of a user array and adds a user ID if there is space available. The data in my JSON file is structured around MongoDB and contains 24 entries (hours). Each entry ...

Utilizing dynamic, MongoDB-inspired expressions to eliminate specific elements from an array

In the process of creating a lightweight database similar to MongoDB, I am incorporating an object-oriented query language where references can be functions or object references: foo.users.find( args ); foo.users.remove( args ); The 'args' para ...

Is there a way to identify a location in close proximity to another location?

With a position at (9,-3), I am looking to display all positions surrounding it within a square red boundary. However, I am struggling to find the algorithm to accomplish this task. Any help or alternative solutions would be greatly appreciated. Thank you ...

Is it possible to have scope inherit from an object in AngularJS?

Imagine creating an app like this: <script> myArray=<?php echo $array;?>; app={ myArray:myArray, myIndex:myArray.length-1, back:function(){this.myIndex--;console.log("You clicked back");}, forward:function(){this.myIndex++} } ...

Obtain the value of a URL parameter on a webpage without needing to refresh the

I have a list of records on a webpage, each with a unique URL pointing to another page with a parameter in the URL. When any of these records are clicked, I want to display the value of the URL parameter in an alert without reloading the page. <script& ...

Difficulty arises when attempting to employ JSON.parse() on an array encoded utilizing PHP's json_encode() function

My Vue component retrieves data from Apache Solr, where the field I'm working with is an array generated using json_encode() in PHP. Here's my component method: data () { return { slideshow: {}, slides: {} } } ...

Enhancing code with new Javascript functionality

Currently utilizing the WordPress Contact Form 7 plugin and in need of updating my existing JavaScript code to include an onclick function and data-img attribute for checkboxes. Due to the limitations of Contact Form 7 shortcode, adding attributes beyond i ...

How can jQuery input be incorporated in a form submission?

My current form includes a field for users to input an address. This address is then sent via jQuery.ajax to a remote API for verification and parsing into individual fields within a JSON object. I extract the necessary fields for processing. I aim to sea ...

Creating three-dimensional text in Three.js

My script is based on this documentation and this resource. Here is an excerpt of my code: <script src="https://raw.github.com/mrdoob/three.js/master/build/three.js"></script> <script> var text = "my text", height = 20 ...

Rails 4 application encountering issues with rendering views when making a $.ajax request

I am a beginner in Rails and I am in the process of sending model data to a controller method from JavaScript for rendering a list of results... function submitResults() { resultURL = "/result"; resultData = JSON.stringify(results); $.ajax({ typ ...

Flask application failing to return JSON error messages

I am currently developing a Flask application and utilizing this code snippet to ensure that all errors are returned in JSON format instead of HTTP. Although I am still learning about Flask, my understanding of the snippet is that it should replace all er ...

Finding a JSON file within a subdirectory

I am trying to access a json file from the parent directory in a specific file setup: - files - commands - admin - ban.js <-- where I need the json data - command_info.json (Yes, this is for a discord.js bot) Within my ban.js file, I hav ...

Conceal the div by clicking outside of it

Is there a way to conceal the hidden div with the "hidden" class? I'd like for it to slide out when the user clicks outside of the hidden div. HTML <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.c ...

Exporting a VueJS webpage to save as an HTML file on your computer

Scenario: I am working on a project where I need to provide users with the option to download a static export of a webpage that includes VueJS as a JavaScript framework. I attempted to export using filesaver.js and blob with the mimetype text/html, making ...

Why isn't my Bootstrap dropdown displaying any options?

I am new to web development and attempting to create a button that triggers a dropdown menu when clicked. I have tried the following code, but for some reason, the dropdown is not working correctly. Can anyone help me identify the issue or correct my code? ...

Error occurred when attempting to load JSON data from file

Consider the json file test.json which contains the following data: {'review/appearance': 2.5, 'beer/style': 'Hefeweizen', 'review/palate': 1.5, 'review/taste': 1.5, 'beer/name': 'Sausa Weize ...

Ensure that all content is completely loaded before displaying it using Angular 2

As an Angular developer, I am facing a challenge in my component where I am generating an image through a service HTTP call. Unfortunately, the image generation process takes longer than the site load time, causing the image to not appear immediately on th ...

My applications are not firing the deviceready event as expected

Struggling to incorporate a cordova plugin into my vue.js project using vue-cordova. Specifically, I am attempting to utilize the open-native-settings plugin to access device settings on iOS or Android. While it works seamlessly in the demo app provided b ...