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

Is it possible to modify parameter values while transitioning?

While transitioning, I need the ability to modify parameter values. After researching the documentation, I discovered a method called `params('to')` that allows accessing target state's parameters. This is how it looks in my code: $transiti ...

Steps to implement jQuery after executing the command "npm install jquery"

Greetings! I recently utilized npm install jquery to add jQuery to my project. However, I noticed that it was downloaded into node_modules\jquery along with some unnecessary files. My goal is to only move node_modules\jquery\dist\jquer ...

Assign the value/text of a div element by using JavaScript/jQuery within a PHP loop

I'm struggling to figure out how to set the value/text of a div using javascript/jquery inside a loop. Can anyone offer some guidance on this issue? Goals: Extract data from a database. Use javascript/jquery to assign the extracted data to an eleme ...

What could be causing issues with my application when using server-side rendered styled-components with Next.js?

I am in need of assistance with an error I've encountered. Every time I try to access the homepage of my Next.js app, it breaks and displays a cannot read data map of undefined error. The browser consistently directs me to the _document.js file, but I ...

In JavaScript, the event.defaultPrevented property will never be set to true

I've been experimenting with events in my script, but I'm struggling to understand the functionality of event.preventDefault()/event.defaultPrevented: var e = new Event('test'); e.defaultPrevented; > false e.preventDefault(); e.d ...

problem with sending JSON data as a string

I am trying to send a property of type 'string' to a WCF server. The string will contain JSON data, but I keep encountering this error: The server has encountered an error while processing the request. The exception message is 'There was an ...

Encountering a Mongoose issue while attempting to load model files from a separate Mean.js project using the require function

I am currently working on a Mean.js project and in the process of familiarizing myself with this environment. To conduct some experiments, I created a parallel project for testing purposes in a separate folder where I am not using the Mean.js framework but ...

Selecting an entire row in a Kendo grid

Is there a way to configure kendoGrid to highlight the entire row when clicked on? I have tried setting: scrollable: { virtual: true } and disabled paging, but it doesn't seem to work as intended. You can view an example here: Kendo UI Dojo When ...

Utilizing conditional statements and time to dynamically alter the class of an object

I need to change the class of an object based on the time, with two classes available: recommendedspot and notrecommended. The code I've written so far is not displaying the image correctly. Can someone help me troubleshoot this issue? Here is my cur ...

What is the best way to retrieve the ID of the input element using a jQuery object?

After submitting a form with checkboxes, I retrieve the jQuery object containing the checked input elements. var $form = $(e.currentTarget); var $inputs = $form.find("input.form-check-input:checked") Here is an example of how the inputs are stru ...

Filling form fields with array data (AngularJS)

Although I'm new to AngularJS, I'm struggling to figure out how to handle a list of arrays returned from the searchAll function. console 0: {mobile: "12345678", lastname: "last01", firstname: "first01"} 1: {mobile: "87654321", lastname: ...

"Utilizing the __proto__ property in Express.js for handling request

One issue that I've encountered is with the request.body generated by the express.urlencoded() middleware. Sometimes, it adds "__proto__" at the end of the request.body object, which makes it impossible to directly use it to initialize a mongoose mode ...

Pictures will be displayed briefly for 1 second prior to the initiation of the JavaScript animation

I recently built a website using gatsby.js and incorporated bounce.js to animate some images on the page. Bounce.js is a JavaScript library that offers DOM animation functionalities. Although everything appears fine when I view the site locally, once I de ...

There seems to be an issue with Ajax functionality within the Webix framework

Exploring webix for the first time has been quite an interesting journey. I am carefully following the guidance provided in the getting started document to create my own webix program. By placing my code in an HTML page and two JSON files as instructed, he ...

Using nightwatch.js to verify elements across different parts of a webpage

Currently engaged in working with nightwatch.js and encountering an issue with a particular page file structure: sections: { table: { selector: '.sr-filterable-data-layout--collection', elements: { header: { ...

Finding the inverse value from the Lodash get() function

My current approach involves utilizing the lodash get() method to retrieve values from an object. However, there are instances where I need to obtain negated values. Unfortunately, simply applying a negate symbol or negate method after retrieving the valu ...

"Enhancing the speed of the JavaScript translate function when triggered by a scroll

I am facing an issue with setting transform: translateY(); based on the scroll event value. Essentially, when the scroll event is triggered, #moveme disappears. For a live demonstration, please check out this fiddle: https://jsfiddle.net/bo6e0wet/1/ Bel ...

Looking for assistance on how to use Express JS to make a post request to insert data with an array of objects into a database. Can anyone provide guidance?

While utilizing ExpressJS for serverside functionality, I encountered an issue when making a post call with multiple objects in an array. The error message displayed is as follows: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to t ...

Determine if a user's inputted number matches a randomly generated number using Javascript

I am trying to generate a random number, prompt the user to input a number, compare the two, and display a popup indicating whether they match or not. Below is the code that I have written for this functionality. function generateRandomNumber() { ...

Creating a functional dropdown form in Ruby On Rails: A Step-by-Step Guide

Having an issue with implementing a dropdown form in the navigation bar of my Rails application. The problem arises randomly - sometimes it works smoothly, while other times I have to refresh the page for it to function properly. The Rails version being u ...