Navigating through Javascript object properties using Numbers and Dashes

For a student project, I'm utilizing the NASA Near Earth Object array but encountering difficulties accessing nested objects with date and hyphen keys like:

2016-09-08 : [...]

When trying to access these objects, I receive an 'undefined' error message.

Below is the API call I am making:

$(document).ready(function NASAtest() {
    $.ajax({
        type: "GET",
        url: "https://api.nasa.gov/neo/rest/v1/feed?start_date=2016-09-07&end_date=2016-09-08&api_key=DEMO_KEY",
        asynch: false,
        contentType: "application/javascript",
        dataType: "json",    
        success: function(data) {
           console.log(data)
           var recordList = data.near_earth_objects;
           console.log(recordList);
           var recordList2 = data.near_earth_objects[2016-09-08];
           console.log(recordList2);

            }     
    });  
});

Here is some sample API data:

{
    "near_earth_objects": {
        "2016-09-08": [
            {
                "neo_reference_id": "3726710",
                "name": "(2015 RC)",
                "nasa_jpl_url": "http://ssd.jpl.nasa.gov/sbdb.cgi?sstr=3726710",
                "absolute_magnitude_h": 24.3,
                "is_potentially_hazardous_asteroid": false,
            } ] } }

Feel free to check out the fiddle link for more details: https://jsfiddle.net/lollyborch/v640ocfr/

You can also view the JSON data directly from the NASA API here:

My goal is to eventually iterate through all the date information to extract specific keys like "absolute_magnitude_h" and "is_potentially_hazardous_asteroid" within a given date range. However, my current roadblock lies in accessing the date key itself.

I've experimented with using square brackets instead of dot notation based on resources such as here and here, but I seem to be missing something crucial. Any guidance or insights on the right approach would be highly valuable.

Answer №1

Remember, the property is named 2015-09-08, but you're trying to access key 1998 (2015 - 9 - 8). Make sure to enclose it in quotes to avoid evaluating the expression and using the result as the property name:

data.near_earth_objects["2015-09-08"]

Keep in mind that even though you mentioned dot notation, in this case, you must use bracket notation instead of dot notation. The equivalent property name won't work with dot notation.


However, if you progress further along this path, you'll likely end up iterating through the object's contents rather than relying on hardcoded names. This approach resolves the issue organically:

for (var neo in data.near_earth_objects) {
    //neo now represents something like "2016-09-07"
    console.log(neo, data.near_earth_objects[neo])
}

Answer №2

When utilizing bracketed notation, it is recommended to enclose the key you wish to access in quotes :

var dataRecord = information.near_earth_objects['2016-09-08'];

You can view a demonstration of this in action here within the console below :

https://i.sstatic.net/ID7Rg.png

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

Establish a PhantomJS export server that can covert Highcharts into an image encoded as a base64 string

I have been researching extensively on the web as well as checking previous stackoverflow questions and answers, but I am still struggling to create an image base64 string. Initially, I downloaded phantomjs 1.9.7.0 I followed the instructions to start ...

The element 'mesh' is not found within the type 'JSX.IntrinsicElements''

I've been diligently studying the React Three Fiber documentation, but I've hit a roadblock with this particular issue. Take a look at my component https://i.sstatic.net/obiNv.png And here are the dependencies I'm using https://i.sstatic. ...

Attempting to execute the .replace() method but encountering difficulties

Looking for help with some HTML code: <li><a href="#" class="lstItem">Testing jQuery [First Bracket]</a></li> <li><a href="#" class="lstItem">Loving jQuery [Second one]</a></li> I need to remove the text in ...

Move the modal dialog so it appears closer to the top of the page

I am facing a challenge with my jQuery modal dialog. While it is loading properly, I am restricted to using an older version of jQuery (1.12.4) and cannot upgrade it. My goal is to center the modal close to the top of the page, similar to how it is positio ...

What are the differences between jQuery, jQuery Mobile, and jQuery UI?

As someone fresh to web development, I find myself overwhelmed by the numerous frameworks available. I am interested in learning about the distinctions between these frameworks and how they can benefit my projects. Additionally, I am curious as to why jQu ...

The Angular2 view is failing to display updated data from a shared service

I've been struggling to show data from my shared service, but it's not displaying. Can someone please help me out? I've been stuck on this for the past few days. I've tried NgZone and ChangeDetectorRef, but they haven't worked for ...

What is the reason for the scrollTop property having a decimal component?

Encountering an issue while trying to scroll down a div with a large amount of data after pressing play on a video. Noticing an unusual problem where the scrollTop value is 211.25, while the scrollHeight is 711 and clientHeight is 500px To address this, ...

Utilizing Github Pages as an API, understanding the concept of rate limiting

I am currently developing an Android app with an expected user base of around 1-2k per day. My requirement is a JSON file hosted at . Are there any restrictions to consider when hosting this file? Are there more efficient methods for hosting the JSON to s ...

There was an issue with parsing the data due to a JSONException stating that the value of type java.lang.String cannot be converted

I've been encountering an error while working with PHP, MySQL, and JSON for the past two days. Here are the snippets of my code: require "includes/connexion.php"; $requete="SELECT * FROM contacts;"; $rep=$pdo->query($requete); while($data=$rep-&g ...

Improve Your Typescript Coding with Visual Studio ReSharper: Automatically Import Classes from External Modules using "from" Instead of "require"

While utilizing JetBrains ReSharper Ultimate 2018.3.4 and executing the command Import 'class '' declared in external module ''' and all other types, it defaults to using require for import statements. However, I would prefer ...

Determining the current element's index as I scroll - using Jquery

If I have a series of divs with the class name 'class' that are fixed height and enable auto-scrolling, how can I determine the index of the current 'class' div I am scrolling in? Here is an example: var currentIndex = -1; $(window).sc ...

Encountering issues with parsing a JSON object while utilizing the templateHTMLrenderer feature in Django

I'm just starting out with django and JSON, and I'm attempting to send a list of patients in JSON using the code below: class JSONResponse(HttpResponse): """ An HttpResponse that converts content into JSON format. """ def __init_ ...

Using Vue to create a search feature within a table

I am facing an issue with the search functionality in my Vue template. Despite implementing the necessary code, the search feature is not working as expected. <input type="text" class="dv-header-input" v-model="query.search_input" @keyup.enter="fetch ...

An array of Promise<Employee> cannot be used as a parameter for an array of type Employee[]

I am currently facing an issue with loading my Collection of Employees from a Firestore Database and fetching a 'Workday' for each Employee, which is stored as a Document in a Subcollection named 'Employees'. Below is the code snippet I ...

Remove a JSON entity if a specific value within the entity corresponds to a specified value (using jq)

One of the objectives is to remove an entire object from a JSON file that includes a specified key/value pair in a JQ script. For instance, any objects with /unwanted-path/ in the path should be eliminated: input.json: [ { "path": & ...

Unable to retrieve accurate Boolean data through ajax request

Imagine a scenario where we are working with the following Ajax request: $.ajax({ url:'myURL.php', data:{ ac:'do', isDoable:false } }); Now, on the backend, when processing the call data, the isDoable param ...

Unclear result encountered within promise sequence

I built a simple employee profile generator app, and everything seems to be working fine until the promise for generatePage(employeeData) is not passing the data correctly. Can anyone provide insight into why this might be happening? I have also attached a ...

What about those ready-made HTML components that have not been revealed yet?

If I have a form with property elements that need to be duplicated, and each property element is a div containing input elements. When the user clicks on an "Add Properties" button, I want another instance of this properties element to be created. The que ...

issue with for loop in jquery ajax not processing complete response data

I have a total of 9 columns in my table, namely choosen_emails_1, choosen_emails_2, choosen_emails_3, booking_address, booking_number, booking_message, booking_date, request_date & user_email The for loop is programmed to iterate and display all colum ...

The Ajax response is functioning properly, however it is not being displayed

Within my web application, there exists a "Mark as Favorite icon". Upon clicking this button, it disappears and triggers an ajax request. jQuery('.favr').click(function() { var user_IDs = jQuery(this).attr('id'); ...