I'm seeking assistance with handling a intricate JavaScript Object that is retrieved from Firebase

As a newcomer to the world of Firebase and JavaScript, I am facing challenges in accessing data from an array of complex objects.

Specifically, I need to retrieve the Date '02-01-2018' from each record. While I can retrieve the key, I am unsure how to access this particular date. I have shared screenshots of my database and the returned values for reference:

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

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

{
"dailyPrices": {
"01-50005": {
"04-01-2018": {
"brands": "",
"editorID": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="086269666d6d6e486269666d6d6e266b6765">[email protected]</a>",
"name": "dddf",
"phone": "",
"place": "errr"
},
// more data follows in a similar format
}
}
}
<input type="text" name="ordDetailTXT" id="ordDetailTXT" value="dailyPrice">

Code

function findOrderDetails(parentKey) 
{
   var returnArr = [];
      var fetchRecord = database.ref(parentKey);
        fetchRecord.on('value', function(snapshot) {
            var item = snapshot.val();
            item.key = snapshot.key; 
            returnArr.push(item);            
    });
}

function btnClickedOrdDetails(){
  var parentkey = ("#ordDetailTXT").val();
findOrderDetails(parentKey);
}

Answer №1

To make it work and create the database structure as needed, simply insert your Firebase credentials into firebase.js. Unfortunately, I am unable to provide Firebase credentials here.

View the working gif here

var returnArr = [];  
function LookForDates()
{
findPrices();
return false;
}

function findPrices(){

returnArr = [];  
var database = firebase.database();
var strtDate = $('#strtDate').val().split('-');
strtDate = strtDate[2] + '-' + strtDate[1] + '-' + strtDate[0];

var endDate = $('#endDate').val().split('-');
endDate = endDate[2] + '-' + endDate[1] + '-' + endDate[0]; 
  
  var fetchDeleted = database.ref('dailyPrices');
  fetchDeleted.on('value', function(snapshot)
  {
    snapshot.forEach(function(snapshot) {
        var item = snapshot.val();
        item.key = snapshot.key;
        item.parentKey = snapshot.key;
         snapshot.forEach(function(child) {
                    item.childKey = child.key;
                });
                if(item.childKey >= strtDate && item.childKey <= endDate)
        {
        returnArr.push(item);
        }
    });
  });
  createPricesTable(returnArr);
}
function createPricesTable(returnArr)
{
$('#DateList')
    .find('option')
    .remove()
    .end()
    .append('<option value="">Select a district</option>')
    .val('whatever');
    returnArr.forEach(function(child) {
                   $('#DateList').append('<option value="'+ child.childKey +'">'+ child.childKey +'</option>');
                });
    }
    function DateSelected(value){
    //perform some functionality
    }
<!DOCTYPE html>
<html>
<head>
    <title>Welcome to Maps Website</title>
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.7.5/css/bootstrap-select.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.bundle.min.js" integrity="sha384-3ziFidFTgxJXHMDttyPJKDuTlmxJlwbSkojudK/CkRqKDOmeSbN6KLrGdrBQnT2n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.7.5/js/bootstrap-select.min.js"></script>
    <link rel="stylesheet"
          href="https://fonts.googleapis.com/css?family=Roboto+Mono&subset=cyrillic">
    <script src="https://www.gstatic.com/firebasejs/4.8.1/firebase.js"></script>
  
</head>
<body>

 <div class="container">
        <div class="row">
              
             <div class="col-sm-12" style="margin-top: 5px;">
         
                           <div class="col col-sm-6"> <input required="" class="form-control" type="date" id="strtDate" name="Date"></div>
                            <div class="col col-sm-6"><input required="" class="form-control" type="date" id="endDate" name="Date"></div>
                            <div class="col col-sm-5"></div>
                            <div class="col col-sm-5"><br />
                            <button type="submit" onclick="return LookForDates();" class="btn btn-primary">Submit</button></div>
             </div>
             <button type="submit" style="display: block-inline; float: right;" onclick="ratelistExport()" id="ratelistExportBtn" class="btn btn-primary">Export to Excel</button>
            <div class="col-sm-12" style="margin-top: 10px;">
            <select name="DateList" onchange="DateSelected(value)" class="form-control" id="DateList" required></select>
            </div>
        </div>
    </div>
<script type="text/javascript" src="JS/Firebase.js"></script>
    <script type="text/javascript" src="JS/JSFidlle.js"></script>
</body>
</html>

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

Guidelines on extracting information from a POST request, evaluating it based on a specified criteria, and providing a corresponding feedback

I'm on the hunt for a simple solution to facilitate communication between the front-end and back-end. What I envision is creating a basic JavaScript front-end client where a user can enter a number between 1 and 10,000 to guess a random number genera ...

Capture the occurrence of a form not being submitted to the server because of validation issues

I have a simple ASP.NET MVC form that includes validation. The validation is set up with attributes/data annotations in the viewmodel, and I have both client-side and server-side validation enabled on my website - a common setup. When the form is submitte ...

Creating a conditional statement in jQuery that will append text to a specific DIV element after a form has been successfully

I currently have a form set up that is functioning properly, but I am looking to make some changes. Instead of redirecting the user to a new page with a success message upon submitting the form, I want the success message to be displayed in a div next to t ...

Building a REST application using the CodeIgniter framework with database integration

I successfully created a REST app using CodeIgniter and a database by following the instructions provided at https://github.com/chriskacerguis/codeigniter-restserver. Everything works perfectly and it's wonderful. Currently, my JSON file shows static ...

How to submit the next row using jQuery AJAX only when the previous submission is successful without using a loop - could a counter

Currently, I am dealing with loops and arrays. My goal is to submit only the table rows that are checked, wait for the success of an Ajax call before submitting the next row. Despite trying various methods, I have not been successful in achieving this yet. ...

Issue: Nav component did not return any content during rendering. This typically indicates that a return statement is absent. To render nothing, you can return null

Encountering an error in my code: Error: Nav(...): Nothing was returned from render. This typically indicates a missing return statement or the need to return null. I am trying to create a styled components navbar but struggling to correct this issue... B ...

Platform error: Responses not specified for DIALOGFLOW_CONSOLE

I've been struggling with this issue for almost a day now and I'm at a loss for what else to try. For some reason, Dialogflow Fulfillment in Dialogflow ES is refusing to make any HTTP calls. Every time I attempt, I receive the same error message ...

What is the method for incorporating an infowindow into a data layer using Google Maps API?

I seem to be having trouble with incorporating an info window into a data layer containing information from a geojson link. Despite my efforts, the info window does not appear as intended in the code snippet below. To address this issue, I followed the in ...

Am I using the if statement correctly?

Can someone confirm if I am using the if statement correctly in this script? Or is it not possible to use an if statement within this code? <script type="text/javascript" charset="utf-8"> $(document).ready(function () { $('#customerTable&ap ...

Uploading Multiple Files Using ReactJS

I am currently facing a challenge in looping through multiple file uploads within React JS. My goal is to iterate through each file uploaded, ensuring that only PNG, JPG, and MP3 files are being added. Additionally, I need to restrict PNG/JPG files to 5MB ...

Processing JSON text input using ActionScript (AS3) object

Hey everyone, I'm facing an issue with ActionScript (AS3) / JSON and need some help. It might be a simple fix, so apologies in advance if this question seems novice. My goal is to gather multiple text strings, organize them into an object, and then s ...

Executing JavaScript code from an external file using AJAX

I've been struggling with this issue all day and just can't seem to figure it out. I have a webpage with a <div id="ajax"></div> that is being populated by a tab-based menu pulling in a snippet of HTML code from an external file co ...

Using jQuery and CSS to Filter and Sort Content

I need help with filtering a list of content based on their class names. The goal is to show specific items when a user clicks on one of two menus. Some items have multiple classes and users should be able to filter by both menus simultaneously. Currently ...

Utilizing JSON object retrieval within a Node.js server

Recently, I started working with Node server. I have written a program that fetches data from a database like this: connection.query("SELECT * from login where username='" + uname + "' and password='" + pwd + "' ", [uname, pwd], functi ...

Strange behavior in Vue observed. The v-if directive is not properly monitoring changes

I am facing a perplexing issue. I have a basic service and a Vue component. In the template, there is a v-if directive that monitors a variable in the service (if it is true, a div should be displayed, otherwise not). Everything works fine when I initial ...

Encountering an error while configuring webpack with ReactJS: Unexpected token found while

I'm attempting to update the state of all elements within an array in ReactJS, as illustrated below. As a newbie to this application development, it's challenging for me to identify the mistake in my code. closeState(){ this.state.itemList.f ...

Decoding a barcode using JavaScript

Currently, I am facing an issue with my barcode gun scanner. It reads barcodes into input fields but returns each digit separately instead of as a whole string. This has been quite bothersome for me. For instance, when I scan the barcode of a bottle of wa ...

While v-carousel adjusts to different screen sizes, the images it displays do not adapt to

Whenever I implement v-carousel, everything seems to be working well, but there is an issue on mobile. Despite the carousel itself being responsive, the images inside do not resize properly, resulting in only the center portion of each image being displaye ...

What about a CSS element that is partially fixed?

I distinctly recall coming across an example of this not too long ago, although I am struggling to locate the specific website. It involved a button or something of that nature situated at the top of the screen, which then remained in place as you scrolle ...

res.json transmitting outdated information

Hey there, I'm encountering a perplexing issue with res.json in Express. Let me show you my /login route: router.post('/login', function (req, res) { if (req.body.user) { var newUser = (typeof req.body.user === 'string&apo ...