Retrieving the value of a specific property nested within a JSON object using basic JavaScript

Hey there! Thanks for taking the time to check out my question. I'm diving into JavaScript and I've hit a roadblock trying to solve this particular problem:

I'm looking to extract the value of a property nested within a JSON object under a dynamically changing property name. Here's the JSON object:

{
  "batchcomplete": "",
  "query": {
    "normalized": [
      {
        "from": "Theodore_Rubin",
        "to": "Theodore Rubin"
      }
    ],
    "pages": {
      "11820415": {
        "pageid": 11820415,
        "ns": 0,
        "title": "Theodore Rubin",
        "contentmodel": "wikitext",
        "pagelanguage": "en",
        "pagelanguagehtmlcode": "en",
        "pagelanguagedir": "ltr",
        "touched": "2016-02-12T17:34:52Z",
        "lastrevid": 138813300,
        "length": 34,
        "redirect": "",
        "new": "",
        "fullurl": "https://en.wikipedia.org/wiki/Theodore_Rubin",
        "editurl": "https://en.wikipedia.org/w/index.php?title=Theodore_Rubin&action=edit",
        "canonicalurl": "https://en.wikipedia.org/wiki/Theodore_Rubin"
      }
    }
  }
}

My goal is to capture the value of the fullurl property in a variable. While I know that using bracket and dot notation like query.pages["2123909"].fullurl can access it, the challenge is that the property name changes with each JSON request.

How could I retrieve the value of the fullurl property without knowing its parent property name?

Your assistance is greatly appreciated!

Answer №1

When dealing with a single key, the first element can be accessed using Object.keys on the data.query.pages object.

var info = {
        "status": "success",
        "result": {
            "details": [
              {
                  "id": 12345,
                  "name": "John Doe"
              }
            ],
            "summary": {
                "12345": {
                    "id": 12345,
                    "age": 30,
                    "occupation": "Engineer"
                }
            }
        }
    };

console.log(info.result.summary[Object.keys(info.result.summary)[0]].age);

Answer №2

In cases where the object only contains a single property name, it is recommended to retrieve the property name and access the property using bracket notation:

var key = // reference https://stackoverflow.com/q/6765864/218196
query.pages[key].fullurl

For objects with multiple properties, it is best to iterate over the object using a method like for...in. You can find more information on how to access and manipulate nested objects, arrays, or JSON in this Stack Overflow post.

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

Avoiding the use of if statements in Javascript

I've recently started learning Javascript and I'm facing an issue with my code. I want to create a functionality where clicking on an image on one page redirects you to another page and shows a specific div based on the clicked image. To achieve ...

Error: Missing root tag after converting XML to JSON and saving it to disk

My goal is to develop a straightforward XML to JSON converter that reads from one folder and outputs to another. The conversion process appears to be functioning properly, but I am struggling to include the root tag of the XML in the output. Below are some ...

Tips on how to choose all elements that do not include a specific value or group of values in cypress

Here's my situation: selector: ".list > div" const velue = [6, 9, 21] Each div contains a different value. I want to remove elements that contain a specific value, then select the first remaining element and click on it. It should look ...

Changing variables from a different file in node.js: a guide

Currently utilizing the discord.js library for my project. Although I can refer to it as such, I am encountering issues when trying to access certain files. For example, let's consider a file named calc.js. In this scenario, I aim to retrieve a var ...

Encountered an error when attempting to access property 'connect' of an undefined value

I encountered an issue with pg.connect not being defined in the Handler module. My goal is to set up a table using postgres in fastify. In my routes handling folder, I manage the routes and send API requests. The error occurs when I navigate to http://loc ...

Tips for controlling the upload of a .exe.png file or converting a .exe file to a png file for uploading in angular 8

I had originally set up restrictions to only allow image file types such as JPG, JPEG, PNG, and TIFF. However, I discovered that users were able to upload .exe files simply by renaming them. For example, changing dell.exe.png or dell.exe to dell.png allo ...

Guide to building a nested React component

My custom dropdown component requires 2 props: trigger (to activate the dropdown) list (content to display in the dropdown) Below is the implementation of my component: import { useLayer } from "react-laag"; import { ReactElement, useState } fr ...

Step-by-step guide on generating a fluid list with Express and HTML

Looking to create a dynamic list by fetching data from a JSON file. I want the list items to redirect me to specific content based on their IDs when clicked. However, my current approach is not working as expected, and the list needs to be truly dynamic. ...

Creating regex to detect the presence of Donorbox EmbedForm in a web page

I am working on creating a Regex rule to validate if a value matches a Donorbox Embed Form. This validation is important to confirm that the user input codes are indeed from Donorbox. Here is an example of a Donorbox EmbedForm: <script src="https: ...

Output the result of a PHP script inside a JavaScript code

I'm having trouble getting the code below to display the success word. Can anyone spot what's wrong with it? Appreciate any help in advance. <script type="text/javascript"> function verification(){ var s = document.test_form.textfiel ...

The improper utilization or replacement of Jest mock in an Angular standalone component's unit test is causing issues

Presented here is a streamlined Ionic/Angular component with unnecessary code removed. import { IonicModule, ModalController } from '@ionic/angular'; @Component({ selector: 'my-component', templateUrl: 'my-component.html' ...

Challenge with row identification in Datatables when rowId begins with a number

In compliance with the Datatables specifications, each row in my table can be assigned a unique ID: $('#myTable').DataTable( { ajax: '/api/staff', rowId: 'staffId' } ); However, it is mentioned in the same specificat ...

I am experiencing an issue with my jQuery loop code not functioning properly when using the .each method within the loop

I am struggling with the following code. <input type="text" name="1" class = "inp<?=$p?>"> <input type="text" name="2" class = "inp<?=$p?>"> <input type="text" name="3" class = "inp<?=$p?>"> <input type="text" na ...

Implementing append operations in JavaScript without relying on the id attribute

Is there a way to specify the second div without assigning it an ID or using any attributes, and then perform an append operation inside it? For instance, indicating that the p element should be appended within the second div without relying on an ID or ...

Tips for redirecting to a 404 page when encountering invalid data in getStaticProps

For my Next.js application, I need to retrieve all articles written by a specific author. The author's ID is obtained from the request parameters. I have already pre-generated some authors using getStaticPaths. Within the getStaticPaths function, I h ...

The deployment on heroku encountered an error during the build process

I'm attempting to deploy my React application on Heroku, but I keep encountering the following errors: -----> Installing dependencies Installing node modules npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ...

What is the best way to transfer information from node.js to HTML?

This is a sample code in Node.js var http = require('http'); var request = require("request"); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('Hello World!& ...

Selecting default values from the Vuex store in Vue-Multiselect

Picture a Vuejs-Application equipped with Vuex. I am aiming to incorporate a mulitselect-dropdown. Here's a basic example inside the Vue-component: <template> <div> <multiselect v-model="values" :options="options"> ...

Differences between Cypress and JQuery objects, and the significance of the cy.wrap function

Currently diving into cypress and experimenting with various testing methods. If anyone could lend me a hand with the following inquiries: 1. I've come to understand that most cypress objects utilize jQuery objects for DOM operations, but what sets t ...

Locate records in MongoDB by leveraging the power of Mongoose

Managing two distinct databases, one for products and another for categories. The product schema is defined as follows: const productSchema = new mongoose.Schema({ name: { type: String, required: true }, description: { type: String, required: true }, ...