Unable to retrieve Firebase keys from the snapshot

Within my firebase DB, I have the following data stored:

    {
  "vehicles" : {
    "fz20tqpxUChOM98fNUYGQhtZ83" : {
      "amount" : 31,
      "timeStamp" : "2017-07-18T20:31:34Z"
    },
    "sw30tqpxUChOM98fNUrGQhtk33" : {
      "amount" : 45,
      "timeStamp" : "2017-07-18T20:31:34Z"
    }
  }

To retrieve a snapshot of this data, I am using the .on method:

  var ref = database.ref('vehicles');
  ref.on('value', function(snapshot) {

    var obj = snapshot.val();
    for (var key in obj){

        console.log(obj);//prints my obj
        console.log(obj.key);//prints 'undefined' both times (why??)
        console.log(obj.fz20tqpxUChOM98fNUYGQhtZ83);//prints data

        if ('fz20tqpxUChOM98fNUYGQhtZ83' === key) {//Just for testing
          console.log("IT IS ===");                //my 'key' is equal to 
                                                   //the hardcoded key 
        } else {
          console.log("NOT ===");
        }

    }
  });

When attempting to access the keys using console.log(obj.key);, I consistently receive undefined as the output. However, when specifically targeting obj.fz20tqpxUChOM98fNUYGQhtZ83, I am able to retrieve the corresponding data. This issue raises questions about why the key values are not being displayed despite attempts to do so programmatically.

Answer №1

element.property only functions if there is a property in the element specifically named property, as shown here:

{
    property: "bar"
}

To achieve your goal, you should use element[property], which retrieves the value of the property by searching for it in a dictionary based on the variable value instead of directly referencing it.

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

Utilizing JavaScript to dynamically resize an element within a slide as soon as the slider transitions to the following slide

RESOLVED! ISSUE FIXED! While working on my personal website using WordPress and the Smart Slider 3 plugin, I encountered a problem with the positioning and size of an element in the second slide. Despite finding a tutorial explaining how to manually trigg ...

Converting JSON into a C# Class through Deserialization

My API call returns a JSON data array with approximately 500 items: [ [ 1571702400000, "8197.28000000", "8297.99000000", "8000.00000000", "8020.00000000", "346 ...

JavaScript's dependency injection functionality is ineffective

I am looking to create a function named createCoffee which will take a function argument called knowHow. function createCoffee(knowHow){ var x=new knowHow(coffee,beans,milk,sugar); knowHow.create(); } This will allow me to use different knowHow funct ...

Error: The validation of a JSON request failed as schema.validate is not a recognized function

As a beginner, I am currently immersed in a node.js API authentication tutorial. Everything was going smoothly until I had to refactor my code into separate files. Now, every time I send a JSON request via Postman, I keep encountering the error message "Ty ...

Having difficulty handling JSON in Swift with SwiftyJSON?

I am currently exploring Swift and working on parsing JSON data from a private API using the SwiftJSON library. However, I am facing issues with assigning the value of "video_upload_id" from the JSON response to the variable "videoUploadId". I have provide ...

A guide on extracting/filtering information from JSON files using JavaScript

Is it possible to extract specific data from a JSON file using JavaScript? I have imported a JSON file into my local JavaScript and I am having difficulty in retrieving and displaying certain information. Could someone offer assistance with this? The JS ...

Tips for Preserving Empty Elements When Parsing JSON in R

Currently, I am facing a challenge with parsing JSON data that is structured as an array of arrays. This structure resembles a table of data, where the elements within the arrays can be either empty or contain nested arrays and objects. Below is an example ...

How to send JSON data using file_get_contents in PHP

I am facing an issue while trying to send JSON content via a POST request to a remote REST endpoint. It seems that the 'content' field is not being sent successfully as expected, even though all other headers are being received accurately. The we ...

An innovative way to display or hide a div depending on the multiple selections made in a select2 jQuery field

A select2 jQuery dropdown menu is set up with two options: *For Rent *For Sales If the user selects 'For Rent', specific fields will be displayed below it, as well as for 'For Sales'. The challenge arises when both options are ...

Extract JSON data and assign it to a PHP variable

I am trying to extract a specific value from a JSON object and store it as a PHP variable. When I echo the variable $jne, this is the resulting data: { "rajaongkir":{ "query":{ "origin":"501", "destination":"114", "weight":1700, "cou ...

Having trouble extracting the responseText from the Ajax request

My current challenge involves making an ajax call and receiving an Object in the response. However, when I attempt to access "responseText," it keeps returning as undefined: var results = API.get('users', { username: un, userpass: pw } ); conso ...

Loading data dynamically in the Highcharts ng library allows for real-time updates to the

I'm currently working on integrating highcharts ng into my Angular project, but I'm encountering issues with data not populating. It seems like there might be a problem related to the loading of the DOM and the function call. Here's my HTML ...

Getting JSON data from an ASP.NET C# server and returning it in a success function

Having trouble retrieving JSON data in this code. Any assistance would be greatly appreciated... JavaScript Code success: function (response) { var obj; try { obj = Ext.JSON.decode(response.response.Text); } catch (error) { ...

Exploring the world of Json and html rendering

My service is designed to generate news with close to 30 different types, each requiring specific HTML code for display. When making an AJAX call, I extract the variable parts from the JSON response and use JavaScript to dynamically create and append the n ...

Utilize attributes from an external JSON schema, within the identical hierarchy as the initial schema

In a separate file, I have a remote schema named "person.json". { "id":"#person", "type":"object", "properties": { "name": {"type":"string"}, "gender": { "type":"string", "enum":["m", "f"] }, ...

Is it possible to establish communication between JAVA and Javascript using Sockets?

Recently, I developed a Java application that generates some data and saves it in a text file on my computer. Instead of saving this data in a text file, I am looking to send it via Socket. Here is an example: Java public static void main(String argv[] ...

I'm currently working on validating a registration form using the jqueryValidation engine plugin, and encountering issues with certain validations not functioning as expected

My experience with PHP is still new, and I'm currently exploring how to validate a signup form using the jqueryValidation engine plugin. While I managed to validate some aspects successfully, I've hit a roadblock with the user name validation par ...

Have you transitioned from using hover in jQuery to writing code in Backbone

I am looking to translate this code into the backbone event model without relying directly on jQuery. $(".class").is(":hover") In attempting to achieve this in my view, I have tried registering events (mouseenter, mouseleave), but it seems that these eve ...

Why is the function not being executed despite having the correct syntax?

Hey there! I've developed a function that's supposed to take an array of Student details and display it, but for some reason, it isn't working correctly. Any ideas on what might be causing this issue? Your help is greatly appreciated! fun ...

Looking for assistance with removing hardcoding in HTML and jQuery?

Currently working on a biography page for my company's website that features a grid layout of the employees' profile pictures. Each picture should be clickable, causing the screen to fade to gray and display an overlay with the respective person& ...