Retrieve data from a JSON object created using dot notation

Currently, I am delving into the realm of constructing and interpreting JSON objects for a personal project centered around pet adoption. A close companion has proposed that I construct one in the following manner:

var userPets = {};
userPets['dogs'] = {};
userPets.dogs['Rex'] = {};
userPets.dogs.Rex['breed'] = 'Labrador Retriever';
userPets.dogs.Rex['age'] = '3 years old';
userPets.dogs.Rex['location'] = 'California';
userPets.dogs.Rex['notes'] = 'great with kids and other pets';

I have successfully managed to convert this object into a string, save it, retrieve it, and parse it. However, I am currently at a standstill when it comes to accessing specific pieces of information (such as age). Is it a common practice to build up the object hierarchy using dots from userPets, to userPets.dogs, to userPets.dogs.Rex? Furthermore, how can I effectively access each individual property?

Answer №2

  1. It is not the standard practice to construct the object in that manner since it involves iterative steps, unlike JSON which is a declarative literal (remember: **J**ava**S**cript **O**bject **N**otation). The same final object can be represented as follows:

    userData = {
        "dogs": {
            "Spot": {
                "color": "black",
                "weight": "241lbs",
                "location": "Washington",
                "comments": "this is a big dog, 241lbs, wow"
            }
        }
    };
    

    Keep in mind that "pure" JSON requires double-quote delimited keys, while in-script object literals can use standard identifiers without quotes.

  2. To access them, you can use dotted notation. However, you would need to employ string-indexer property syntax if your objects have keys that do not adhere to JavaScript identifier restrictions (e.g., no spaces, punctuation, must start with a letter, etc):

    console.log( userData.dogs.Spot.color ); console.log( userData.dogs.Spot.comments );

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

Android Volley BasicNetwork encountered an unexpected response code 412 during request execution

I encountered an issue in my logcat while utilizing Volley for request sending. The error message states: E/Volley﹕ [2040] BasicNetwork.performRequest: Unexpected response code 412 for http:/myserver/index.php Strangely, there seems to be no other err ...

Encountering the error message "Type '{ theme: Theme; }' is not compatible with type" while attempting to pass it as a prop to the App component

Trying out a new strategy for my app initialization by incorporating the use of the useLocation hook within my App component. I'm still learning Typescript and encountering a problem. This is what I have so far: // index.tsx const theme: Theme = cre ...

The getJSON method returns a status code of 200, however, it does

After researching extensively, I have yet to find a solution that addresses my specific issue. The core of the problem lies in a piece of PHP code responsible for generating a JSON object. This is what my page currently looks like: <?php $supps = ...

The problem with 'Access-Control-Allow-Origin' on themoviedb

Is anyone else experiencing an issue with the themoviedb api? When trying to load , I receive the error message: "XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' is th ...

The GIF Loader fails to animate while an AJAX request is in progress

Displaying a DIV element containing a loading GIF image while waiting for an AJAX call response. Initially, the DIV element is hidden. Upon clicking a checkbox, the loader DIV is shown, followed by the completion of the AJAX call, and then hiding the load ...

Steps for retrieving a JSON file from a web browser containing data in the JSON format

I need to download a text/json file using a string that contains the data in JSON format. In my controller, I am adding an ArrayList containing objects of the Service Class to the model. Here is the code snippet: @RequestMapping("/Application.html") p ...

Error encountered when attempting to navigate to a new page in Flutter

I encountered an issue with my Gridview builder using JSON data. When I try to navigate to a new page, I receive an error message stating: "Could not find the correct Provider above this SingleItemScreen Widget." To resolve this problem, please follow the ...

Verify whether the preload script has been executed previously (indicating that elements are cached)

My jQuery AJAX function is set to load with the call to .JS on every page in the html document. I am looking to add an if statement that checks whether the files I want to preload are already in cache. This will prevent the script from running its content ...

Is there a way to utilize localStorage to retain a classlist toggle status for a light/dark mode theme switch on the browser?

I am currently working on a portfolio website that features a light/dark mode theme switch. The functionality of the switch is working properly, but it doesn't save the user's preference when they refresh the page or navigate to another section. ...

The page loader failed to load in Chrome due to a timeout, but surprisingly, it loaded

I have added a loader that works perfectly in Chrome, but not in Firefox. In Firefox, the loader keeps loading endlessly without stopping. Here is the HTML code for the loader: <div id="loading"> <img id="loading-image" src="images/ajax-l ...

Is it possible to reduce costs by refraining from calling jQuery each time I want to retrieve an element?

Suppose I am working with the following code block: $('#myBox').css('background', 'grey'); $('#myBox').click( function(e){ console.log( 'Box clicked' ); }); $('#myBox').html(' Just a test te ...

Is it advisable and what is the proper way to shift to a different route within a promise's

Trying to utilize Ember controller to make an API call for user creation and then transitionToRoute upon success. Here is the current setup: import ajax from "ic-ajax"; import Ember from "ember"; export default Ember.Controller.extend({ actions: { ...

Developing an attribute in a constructor using Typescript

My javascript code is functioning perfectly: class myController { constructor () { this.language = 'english' } } However, I encountered an issue when trying to replicate the same in Typescript export default class myController { co ...

Tips for displaying the number of selected values in a select box label (e.g. Choose an Option)

I am currently using the jQuery multiselect API in my application to allow users to select multiple values. However, I am facing an issue where I need to fetch all the selected values when a button next to the multiselect box is clicked. Unfortunately, I h ...

Issue encountered during execution of a mongodb function within a while loop in nodejs

To ensure that a generated id doesn't already exist in the database, I have implemented the following code: let ssid; while ( ssid == undefined ) { let tempSId = assets.makeid(30); MongoClient.connect(mongoUrl, function(err, db) { if ( ...

How can components be utilized with v-edit-dialog?

Hey there, I've been exploring the v-edit-dialog component offered by Vuetify and had a query about its implementation. Currently, I'm structuring my v-data-table in a way where I'm importing a component with props into a template slot. The ...

Javascript callback function cannot access variables from its parent function

As a Javascript newbie, I am currently diving into callbacks for my project. The goal is to retrieve address input from multiple text boxes on the HTML side and then execute core functionalities upon button click. There are N text boxes, each containing an ...

Interactive form created with asp.net and dynamic javascript functionality

Hello, I am a beginner in web development. I have created an application that includes a button. When the button is clicked, a popup window should appear with 2 fields and another button. Once the user clicks the button in the popup window, the data ente ...

The File is not being successfully sent to the controller in MVC due to AJAX returning an undefined value

I recently created an AJAXUpload method within a cshtml file in my C# MVC project: function AjaxUpload(url, method, data, successFunction, errorFunction, skipErrorDlg) { $.ajax({ contentType: false, processData: false, url: url ...

ng-model causing simultaneous changes to all selects

Check out this jsfiddle link Hello there, I'm encountering an issue with my application. I need to create multiple dropdowns using ng-repeat and have them all populated with the same options. The problem arises when one dropdown is changed, all ot ...