What is the process for filling a table with data sourced from Firebase?

I have successfully used the code below to populate a datatable table with data from a JSON file. However, I am now attempting to populate the table with data from Google's Firebase database. The issue arises because new data pushed into Google's Firebase database comes with a push key, which complicates the process for me due to my limited experience with Firebase.

The desired outcome is shown in this image: https://i.sstatic.net/WkWfm.png

The code below creates two arrays objects from the Firebase data - one for the columns and one for the data:

var columns = [];
var data = [];
firebase.database().ref("DataSet2").once("value", function(snap){
    snap.forEach(snapshot => {
        Object.keys(snapshot.val()).map(k => {
              columns.push(Object.assign({}, {"data":k}))
              data.push(Object.assign({}, {k:snapshot.val()[k]}))
        })
    })
})
console.log(columns)
console.log(data)

Despite my efforts, populating the tables using the following code does not work (nothing happens):

Any suggestions on how to achieve this?

$("#example").DataTable({
ajax: {
        url: 'test.json',    
        dataSrc: data 
      },
      "columns": columns
});

HTML:

    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>MK</title>
    <!-- DATATABLES -->
    <link rel="stylesheet" type="text/css" href="https://www.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/dataTables.bootstrap.min.css">
    <!-- RESPONSIVENESS -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/responsive/2.2.1/css/responsive.dataTables.min.css">
    <!-- DATETIMEPICKER -->
    <link rel="stylesheet" type="text/css" href="https://rawgit.com/smalot/bootstrap-datetimepicker/master/css/bootstrap-datetimepicker.css">
    <!-- DATATABLES FREE EDITOR -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/1.5.1/css/buttons.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.2.4/css/select.dataTables.min.css">
    <!-- MYCSS -->
    <link rel="stylesheet" type="text/css" href="style.css">
</head>

<body>
    <input type='text' id="dateTime" class="dateTime" placeholder="Date Time" readonly>

    <div id='tableContainer'>

        <table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
            <thead>
                <tr>
                    <th></th><!-- COLUMN FOR RESPONSIVENESS -->
                    <th>INBOUND</th>
                    <th>ORG</th>
                    <th>STA</th>
                    <th>ETA</th>
                    <th>OUTBOUND</th>
                    <th>DES</th>
                    <th>STD</th>
                    <th>ETD</th>
                    <th>REMARKS</th>
                    <th>GATE</th>
                    <th>WHS</th>
                    <th>TEST</th>
                    <th>ARR</th>
                </tr>
            </thead>
        </table>

    </div>

</body>
<!-- FIREBASE -->
<script src="https://www.gstatic.com/firebasejs/4.9.0/firebase.js"></script>
<!-- JQUERY -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- DATATABLES -->
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap.min.js"></script>
<!-- RESPONSIVENESS -->
<script src="https://cdn.datatables.net/responsive/2.2.1/js/dataTables.responsive.min.js"></script>
<!-- DATETIMEPICKER -->
<script src="https://rawgit.com/smalot/bootstrap-datetimepicker/master/js/bootstrap-datetimepicker.min.js"></script>
<!-- DATATABLES FREE EDITOR -->
<script src="https://cdn.datatables.net/buttons/1.5.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/select/1.2.4/js/dataTables.select.min.js"></script>
<script src="datatablesAltEditor.js"></script>
<!-- MYJS -->
<script src="libs.js"></script>

JS:

 $("#example").DataTable({
select: 'single',
responsive: true,
paging: true,
pageLength: 25,
order: [
    [3, 'asc']
],
ajax: {
    url: 'dbs.json',
    dataSrc: 'dataset1'
},
"columns": [{
        "data": null,
        defaultContent: '',
        className: 'control',
        orderable: false
    }, // RESPONSIVENESS
    {
        "data": "inbound"
    },
    {
        "data": "org"
    },
    {
        "data": "sta"
    },
    {
        "data": "eta"
    },
    {
        "data": "outbound"
    },
    {
        "data": "des"
    },
    {
        "data": "std"
    },
    {
        "data": "etd"
    },
    {
        "data": "remarks"
    },
    {
        "data": "gate"
    },
    {
        "data": "whs"
    },
    {
        "data": null,
        render: function(data, type, row) {
            return data.flight + ' ' + data.org;
        }
    },
    {
        data: "arr"
    }
]

});

JSON:

{
"dataset1": [{
    "inbound": "MK509",
    "org": "ICN",
    "sta": "12DEC17 16:45",
    "eta": "12DEC17 17:35",
    "outbound": "MK509",
    "des": "ARN",
    "std": "12DEC17 18:45",
    "etd": "12DEC17 19:35",
    "remarks": "DELAYED",
    "gate": "S96",
    "whs": "T11",
    "arr": "X"
}, {
    "inbound": "RT8101",
    "org": "DOH",
    "sta": "12DEC17 08:25",
    "eta": "12DEC17 08:25",
    "outbound": "RT8101",
    "des": "ORD",
    "std": "12DEC17 10:25",
    "etd": "12DEC17 10:25",
    "remarks": "COW CHARTER",
    "gate": "S94",
    "whs": "T9",
    "arr": "X"
}],
"dataset2": [{
    "flight": "KIKKER1",
    "org": "ICN",
    "sta": "12DEC17 16:45",
    "eta": "12DEC17 17:35",
    "flight": "KE509",
    "des": "ARN",
    "std": "12DEC17 18:45",
    "etd": "12DEC17 19:35",
    "remarks": "DELAYED",
    "gate": "S96",
    "whs": "T11",
    "ciss": "X",
    "arr": "X"
}, {
    "flight": "KIKKER2",
    "org": "DOH",
    "sta": "12DEC17 08:25",
    "eta": "12DEC17 08:25",
    "flight": "QR8101",
    "des": "ORD",
    "std": "12DEC17 10:25",
    "etd": "12DEC17 10:25",
    "remarks": "COW CHARTER",
    "gate": "S94",
    "whs": "T9",
    "ciss": "X",
    "arr": "X"
}]

The data stored in Firebase can be viewed in this image: https://i.sstatic.net/m0D0T.png

Here are the resulting columns and data arrays: COLUMNS https://i.sstatic.net/mkNiM.png DATA https://i.sstatic.net/aMbBS.png

Answer №1

To ensure that your data is recognized as a JavaScript array, make use of the data option.

Here is an example implementation:

$("#example").DataTable({
   "data": data,
   "columns": columns
});

When retrieving the data, follow this approach:

var columns = [];
var data = [];

firebase.database().ref("DataSet2").once("value", function(snap){
    snap.forEach(snapshot => {
        var rcd = [];
        Object.keys(snapshot.val()).map(k => {
              columns.push(Object.assign({}, {"data":k}));
              rcd.push(Object.assign({}, {k:snapshot.val()[k]}));
        })
        data.push(rcd);
    });
});

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

Instructions on nested keys in iOS for API request

Here is my approach to posting to an API: curl -v -H 'Content-Type: application/json' -H 'Accept: application/json' -X POST http://sub.domain.com/api/v1/sections.json -d "{\"section\":{\"properties\":{\"email&b ...

Exploring Node's Configuration File Reading Process

Trying my best to provide all the details for my question. Being a newbie to NodeJS, I appreciate your kind guidance :D In the process of developing an application in Node, focusing on enabling users to view stats regarding their Plex Media Libraries. The ...

What is the best way to use JavaScript to click on a block and retrieve its attribute value?

Struggling to capture the data-id attribute value of each item on click, despite researching online. Seeking guidance as I navigate the learning process and encounter programming frustrations. document.addEventListener("click", handle); const demo = e. ...

Animation of disappearing blocks covering the entire screen

I am currently working on creating a slider with fading blocks animation similar to the one shown here. The challenge I am facing is making it fullscreen, where the height and width will be variable. This makes using the background-position trick ineffecti ...

Display/Collapse SELECT choices?

Consider this scenario : <select class="form-control" name="blah" ng-model="$ctrl.form.blah" ng-options="item.id as item.name group by item.etype | uppercase for item in $ctrl.opts"></select> My goal is to toggle the display of each GROUP b ...

Exploring the process of extracting specific data from a dynamic JSON response and seamlessly transferring it to another request

After receiving a .json file as a response from an API, I need to parse it and extract a specific parameter to pass as input to the next request. How can this be accomplished using Katalon? When attempting to use: response = JSON.parse("response.json"); ...

Creating Kotlin classes to utilize Gson for converting JSON responses into class objects

I have recently delved into learning Android development, with a current focus on understanding how to consume REST API's. The particular service I am tinkering with, namely The Movie Database, returns responses structured like this: { "certi ...

Encountering issues with JSON serialization in FlexJSON

After creating an Object with attributes such as id, title, content, and isPublic, my program started malfunctioning when attempting to retrieve and serialize data from the database. Each time I connect to the frontend webapp, it loads notes, serializes t ...

What happens to the parent scope in Javascript when declaring a subclass and why does it get overridden?

I have two classes in JavaScript, with one inheriting from the other. The structure is as follows: var Parent = (function(){ var self; var parent = function(){ self = this; self.type = 'Parent'; }; parent.protot ...

Button click event is not being triggered by Ajax rendering

I am facing an issue with my Django template that showcases scheduled classes for our training department. Each item in the list has a roster button which, when clicked, should display the class roster in a div. This functionality works perfectly. However, ...

"Utilizing the power of Twitter Bootstrap and Snap.js for

I am currently working on integrating Snap.js by jakiestfu with Twitter Bootstrap. I have managed to make it work to some extent (I can slide the content and open a drawer through a click event). However, I am facing a challenge where the drawer content re ...

"Troubleshooting: JsonParser using json-c Library in C shows error message 'json_object_object_get(...) not

Having just joined this community, I am currently working on implementing a Json Parser. I stumbled upon a helpful tutorial () for a Json Parser Program. Here is an example of the Json file input: { "DefaultTest": "SS", "Send": { "ip_hl": 4, ...

Fetch data from Firestore when the page loads using the useEffect hook

Below is the simplified code snippet I am currently using: import { useState, useEffect, useContext } from 'react' import { useRouter } from 'next/router' import { firestore } from './firebase-config' import { getDoc, doc } f ...

Tips for emphasizing the current element without disrupting existing styles

Is there a way to highlight an element with a border without causing it to shift? The script seems a bit glitchy when detecting mouse leaving the area. I'm unable to override parent element properties like border or outline. I also can't use pse ...

Pause file uploads, display modal popup, then resume uploading

Is there a way to pause file uploading in order to display file requirements before proceeding? For example, when a user clicks on "upload file", I would like to show them a modal window with details about the file they need to upload. Once they click ok, ...

Collaborate on React-Native components together!

As a newcomer to the world of react, react-native, and nodejs, I embarked on creating my own node module using npm init. Within this module, I developed a component for styling buttons, packaging it with npm pack and linking it in my application's pac ...

What is the best way to incorporate an immediately invoked function expression (IIFE) within the return statement of a React

I currently have a modal that pops up when the user clicks a button on my page and it's functioning perfectly: render() { return ( <div> <section> <button onClick={() => this.refs.simpleDialog.show()}> ...

The issue with React select right-to-left (RTL) functionality is that it

When using react select, I include isRtl as a prop like so: <Select onChange={handleChange} isRtl isMulti options={colourOptions} /> However, only the input receives the rtl direction style and not the options. How can I ensure that both the input a ...

What is the best way to refresh a single component in my application without causing the other components to reload?

I've been working on a review application with Vue.js that fetches random facts from an API (https://uselessfacts.jsph.pl/random.json?language=en) and allows users to provide feedback through radio buttons and text inputs. Once submitted, the feedback ...

Verifying One Time Password (OTP) from MSG91 URL using ReactJS

Currently, I am working on a small project that involves receiving and verifying OTPs from MSG91. While I have managed to successfully receive OTPs using MSG91, I am encountering an issue when trying to verify OTPs - specifically, I keep getting an error ...