Display the properties of the nested object

I am trying to extract and print the postal_code value from the JSON file provided below:

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "286",
               "short_name" : "286",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "West El Camino Real",
               "short_name" : "W El Camino Real",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Old Mountain View",
               "short_name" : "Old Mountain View",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "Mountain View",
               "short_name" : "Mountain View",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Santa Clara County",
               "short_name" : "Santa Clara County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "California",
               "short_name" : "CA",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "94040",
               "short_name" : "94040",
               "types" : [ "postal_code" ]
            },
            {
               "long_name" : "2606",
               "short_name" : "2606",
               "types" : [ "postal_code_suffix" ]
            }
         ],
         "formatted_address" : "286 W El Camino Real, Mountain View, CA 94040, USA",
         "geometry" : {
            "location" : {
               "lat" : 37.3833211,
               "lng" : -122.0782706
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 37.38467008029149,
                  "lng" : -122.0769216197085
               },
               "southwest" : {
                  "lat" : 37.3819721197085,
                  "lng" : -122.0796195802915
               }
            }
         },
         "place_id" : "ChIJieTN_yu3j4AR6cF-aEhdc58",
         "types" : [ "street_address" ]
      }

   "status" : "OK"
}  

Below is the code I have written to fetch and display the response:

$.ajax({
  dataType: "json",
  url: 'https://maps.googleapis.com/maps/api/geocode/json?latlng=37.383253,-122.078075&sensor=false',
  data: latlog,
  success: function (response) {  
  $("#response").html(JSON.stringify(response["results"], null, 4));
  }
}); 

The current output displays the entire object. How can I specifically display only the postal_code value which is 94040?

Answer №1

Your JSON code needs some corrections, please refer to the demo for the correct syntax.

How can I specifically extract the postal_code value of 94040?

To retrieve the postal_code value, you must navigate through the address component and filter out the object with a type of postal_code

Here is a suggested solution:

obj.results[0].address_components.filter( function(obj){ 
  return obj.types.indexOf("postal_code") != -1 
})[0].long_name

DEMO

var obj = {
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "286",
               "short_name" : "286",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "West El Camino Real",
               "short_name" : "W El Camino Real",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Old Mountain View",
               "short_name" : "Old Mountain View",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "Mountain View",
               "short_name" : "Mountain View",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Santa Clara County",
               "short_name" : "Santa Clara County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "California",
               "short_name" : "CA",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "94040",
               "short_name" : "94040",
               "types" : [ "postal_code" ]
            },
            {
               "long_name" : "2606",
               "short_name" : "2606",
               "types" : [ "postal_code_suffix" ]
            }
         ],
         "formatted_address" : "286 W El Camino Real, Mountain View, CA 94040, USA",
         "geometry" : {
            "location" : {
               "lat" : 37.3833211,
               "lng" : -122.0782706
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 37.38467008029149,
                  "lng" : -122.0769216197085
               },
               "southwest" : {
                  "lat" : 37.3819721197085,
                  "lng" : -122.0796195802915
               }
            }
         },
         "place_id" : "ChIJieTN_yu3j4AR6cF-aEhdc58",
         "types" : [ "street_address" ]
      }],

   "status" : "OK"
}  

var long_name = obj.results[0].address_components.filter( function(obj){ return obj.types.indexOf("postal_code") != -1 } )[0].long_name;

console.log(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

Encountering empty values when attempting to submit information using Spring framework

Recently, I developed a CRUD AJAX REST application using the Spring framework. However, I have encountered an issue where the object sent from the client to the server is being filled with null values. Oddly enough, the client side shows a status code of 2 ...

Transforming Several Dropdowns using jQuery, JSON, and PHP

Hey there! I'm looking to update the state depending on the country and city based on the chosen state. <label>Country:</label><br/> <select onchange="getval(this)"> <option value="">Select Country</op ...

The Bootstrap Navbar is causing the navigation bar to span across two lines

I'm having an issue with my navbar taking up two lines on desktop resolution, but fitting perfectly on mobile. I've spent hours going through the code with no success. Any help would be greatly appreciated. The HTML code is provided below. <! ...

"Utilize the power of the ajaxform jQuery plugin to automatically reset form fields

Initially, I'd like to emphasize that this is an original inquiry. My predicament is as follows: I have a chatroom php script where I utilize the ajaxForm jQuery plugin to seamlessly send new messages without having to reload the entire page. Howev ...

Attempting to dispatch data from Vue.js event bus

I am attempting to increase the count of quotes by one and also add the text from a textarea to an array. While the text is successfully added to the array, the number of quotes always remains zero. I have tried combining the two actions in one method as w ...

Utilize Angular service to deliver on a promise

Currently, I have a service that is responsible for updating a value on the database. My goal is to update the view scope based on the result of this operation (whether it was successful or not). However, due to the asynchronous nature of the HTTP request ...

Error message: Trying to call the prepare() function on a null variable within the CRUD system

I have implemented a CRUD system on my website. The main page (avisos.php) displays a table with all the existing records. When a user clicks on the "ADD NEW RECORD" button, the following script is triggered: $("#btn-add").click(function(){ $(".co ...

"How to change the hover background of a select element in Chrome from its default setting to something else

Is there a way to remove the background color on hover and replace it with a different color? .drp-policydetails { border: 1px solid #dddddd; background-color: #ffffff; } <div className="form-group"> <select className="form-control drp-po ...

Send information to a different module

I've created a straightforward form component: <template> <div> <form @submit.prevent="addItem"> <input type="text" v-model="text"> <input type="hidden" v-model="id"> <i ...

What is the best way to distinguish a particular item in a <select> element and include a delete button for each row using jQuery?

1.) I've set up a nested table and now I want to ensure that when the 'Delete' button within the child table is clicked, its corresponding row gets deleted. 2.) I have a <select> tag. The issue is how can I implement validation to che ...

How can you toggle the visibility of a div based on detecting a specific class while scrolling?

My webpage features a sticky header that gains an extra .header-scrolled class when users scroll down. I am looking to switch the logo displayed in the header once it has been scrolled. Below is a simplified version of my HTML code: <header class=".he ...

On the second attempt, Firefox is able to drag the div element smoothly by itself

I have created a slider resembling volume controls for players using jQuery. However, I am facing an issue ONLY IN FIREFOX. When I drag the slider for the second time, the browser itself drags the div as if dragging images. The problem disappears if I clic ...

JavaScript throws an error when attempting to access an object's methods and attributes

Within my Angular.js module, I have defined an object like this: $scope.Stack = function () { this.top = null; this.size = 0; }; However, when I try to use the push method of this object, I encounter an error stating undefined: ...

Switching from PHP to JavaScript before returning to PHP to establish and manage sessions

Currently, I am in the process of resolving an issue I am facing. The problem arises when utilizing the following code for someone trying to sign into the admin panel: <script> function myFunction() { //alert('you can type now, end ...

Retrieving information transmitted via lightstreamer

Currently, I am utilizing an application that is sending data to my browser every second using a technology called "lightstreamer". This technology is unfamiliar to me, but I believe it involves AJAX. The data being sent consists of continuously changing s ...

What is causing the Spring MVC controller method to not process the basic GET AJAX request effectively?

I am currently developing a Spring MVC application and facing an issue while trying to retrieve a String value passed through a JQuery AJAX Request. function addNotes() { console.log("INTO addNotes()"); var currentNoteText = $('#currentN ...

Display the names of files depending on the selection made in the drop-down menu

In order to utilize a value from a select box for a PHP function later on the page, I am seeking assistance. Within my index.php file, there is a standard select drop down containing folder names as values and options. After selecting a folder, I aim to e ...

How to eliminate spaces while preserving line breaks in a textarea using JS or jQuery

I have been trying to figure out how to remove extra spaces from the beginning and end of lines while keeping the line breaks intact. Here's what I attempted: function removeSpaces(string) { return string.split(' ').join(''); } ...

Is it possible to merge two individually operational Jquery form elements into one cohesive unit?

Currently, I am in the process of constructing a form that utilizes Jquery-Elements such as sliders. Additionally, I have incorporated a Jquery-Plugin to enhance the dropdown element. Both components work flawlessly when they are kept in separate files. Ho ...

Encountering issues when attempting to establish the initial date of a react DatePicker based on the user's timezone

I am currently working on a React project and facing an issue with setting the default date of a DatePicker component to the user's timezone received from an API. Despite several attempts, I keep encountering an error whenever I try to inject the date ...