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

Stopping React component click event from bubbling up to document

How do I prevent a click event in a React component from bubbling up to the document? There seems to be an issue that needs fixing! Let's see if we can resolve it on our own. I have a box component with a click event listener, and some link compone ...

Incorporate 3 additional compound filters with shuffle.js

Is there a way to add a third compound filter to the existing shuffle.js code provided below? // ES7 will have Array.prototype.includes. function arrayIncludes(array, value) { return array.indexOf(value) !== -1; } // Convert an array-like object to a r ...

Invoke the forEach method within a lambda function and assign the output to a variable

In order to achieve my goal, I am looking for a way to take an array as input and save the result for future use. Unfortunately, I do not have permission to create additional functions. As a result, the code must accurately reflect what result should be. l ...

Is there a way to effectively incorporate react-native with php and ensure that the data returned by the fetch function is

I'm struggling to make my return value work in this code. Has anyone had success using react-native with php and fetch json? Any tips or advice would be greatly appreciated. PHP $myArray = array(); $myArray['lat'] = $_POST['lat']; ...

Filtering: A JSON file that consists of an array of JSON objects

I have a variable prev_data which is a dictionary containing the following values { "values": [ { "color_code": { "bg_color": "#FFD9E1", "border": null, "label&quo ...

Service Worker Tips: Caching the initial page with dynamic content

I have a single-page application with a dynamic URL generated using a token, for example: example.com/XV252GTH, which includes various assets such as CSS and favicon. This is how I implement the Service Worker registration: navigator.serviceWorker.regist ...

Passport JS receiving negative request

I'm currently experiencing an issue with the passport req.login function. When a user logs in using their email and password, instead of redirecting to /productos2 as intended, it routes to a bad request page. I am utilizing ejs and mongoose for this ...

Why does the second JavaScript form validation not function correctly when compared to the first?

Here is a form that I have created: <form action="next.html" id="userInput" method="post" onsubmit="return validate();"> Age: <input type="text" name="age" id="age"/> function validate() { var age = document. ...

Intrigued by the asynchronous nature of AJAX and the concept of scheduled or timed events

I have a question regarding AJAX and its asynchronous nature... When JavaScript is run while a page loads and triggers an AJAX call, the page continues to load while the server processes the AJAX request. Can this be likened to pseudo-parallelism? What h ...

What is the purpose of Access-Control-Allow-Headers in an HTTP response and why is it important to include it?

I've been working through a tutorial on using express and have come across the following routes: module.exports = function(app) { app.use(function(req, res, next) { res.header( "Access-Control-Allow-Headers", "x-ac ...

Send JSON data that has been refined utilizing jQuery

I am attempting to create a filtered JSON response using jQuery following a successful GET request of the original JSON response. The initial JSON response is an array of products from our Shopify store for the specific collection page the user is viewing. ...

Learn the process of adding a tag to specific text with the help of JavaScript

I am attempting to implement a feature where the selected text will have a tag added to it. Within a textarea, I have some text entered. The goal is that when I select specific text from the textarea and click a code button, it should insert the tags aro ...

producing a NaN result when calling a reducer with an integer value

Could anyone assist me with this react-redux code? I have an input field that accepts numbers and adds them to the counter above. My goal is to reset the counter to 0 if the input is not a number, but currently when I type any character other than an int ...

Raycast in Three.js is struggling to locate object

Whenever I select a 3D model, my goal is to retrieve the object's ID, name, or the actual object itself in order to effectively delete it. function onDocumentMouseDown( event ) { if (enableRaycasting){ event.preventDefault(); mouse.set( ( event.c ...

Complete the submission by either clicking the mouse or pressing the enter key

When submitting a form, I can do so by clicking with the mouse or pressing ENTER. An AJAX call is made to check if a designation already exists in the database. If it doesn't exist, the user can submit the form. Otherwise, the SUBMIT button will be d ...

Parsing data from the JSON Shell command

I have a JSON array that looks like this. [ { "release": "2008.1006", "kernel": "2.6.32-754.3.5", "os": "6.10", "current": true }, { "release": "2008.1006", "kernel": "3.10.0-862.14.4", "os": "7.5", "current": true } ] When I use ${#array[@]} to print th ...

Creating a Form with PHP that Sends AJAX Request

I created a simple form with room equipment options. Here is the code for the form: <form action="javascript:void(0);" method="post"> <fieldset> <legend>ROOM EQUIPMENT</legend> <div class="inline_inputs"> &l ...

Error: The JSON file cannot be located by the @rollup/plugin-typescript plugin

I have recently set up a Svelte project and decided to leverage JSON files for the Svelte i18n package. However, I am facing challenges when trying to import a JSON file. Although the necessary package is installed, I can't figure out why the Typescri ...

Unleashing the Power of Dynamic JSON Data Access

I am facing an issue with my React Child component. Here is the code snippet: const SingleProject =(props)=>{ let data = projectData.VARIABLE_FROM_PROPS.projectDetails; let asideData = projectData.VARIABLE_FROM_PROPS.projectSideBar; useEffe ...

Designating a certain function to a designated button

On my page, I have three different forms with submit buttons in each. There is a code that is supposed to change the value of a button in a specific form when clicked. However, whenever I click on any submit button, all the values in the buttons of the v ...