Dealing with hierarchical JSON data for a ListView display

I am currently seeking a way to retrieve deeply nested JSON data from a firebase database in order to utilize it within a listView. This approach has been successfully implemented throughout my application, but I am facing challenges when attempting to access dynamic properties of the children data.

An example export of the JSON data from my database is as follows:

{
    "T&G Canary Wharf" : {
        "Administrator" : {
            "1550633367665" : {
                "date" : "2019-02-12T12:00:00.000",
                "details" : "Full Day",
                "name" : "Edward Lawrence",
                "status" : "pending"
            },
            "1550633370715" : {
                "date" : "2019-02-13T12:00:00.000",
                "details" : "Full Day",
                "name" : "Edward Lawrence",
                "status" : false
            },
            "1550845072137" : {
                "date" : "2019-02-12T12:00:00.000",
                "details" : "Full Day",
                "name" : "Katie Prescott ",
                "status" : 1
            },
        },
        "Stylist": {
            "1551222170677": {
                "date": "2019-02-19T12:00:00.000",
                "details": "Full Day",
                "name": "Stylist Stylist",
                "status": "pending"
      }
    }
  }
}

In the context of the app user, the group (e.g., T&G Canary Wharf) will always be specified, while the subgroup (such as Administrator & Stylists) varies dynamically for administrators, presenting an obstacle that I am currently grappling with.

Below you can find the code snippet used for reading data from the Firebase database:

The framework employed here is felgo(formerly v-play), and attached is a link to their Firebase documentation:

Felgo Firebase Plugin

App {

    property var adminModel: []
    property var groupName //the group name is assigned onLoggedIn, in this example group name === T&G Canary Wharf

    FirebaseDatabase {
        onLoggedIn: { 
        firebaseDb.getValue("groups" + "/" + groupName, {
                                orderByValue: true
                            }, function(success, key, value) {
                            if(success){
                            console.log("ADMIN MODEL: " + JSON.stringify(value))
                            adminModel = value // my array where I intend to push the data too                              
                            }
                        })
                    }
                }
            }

Further enlightening discussions about accessing or processing nested objects, arrays, or JSON data can be found on:

access/process nested objects, arrays or JSON

(remarkably informative by the way!), especially focusing on the part labeled "What if the property names are dynamic and I don't know them beforehand?"

The challenge I face lies in creating two list entries for Administrator and Stylist subGroups where the child key is also dynamic (reflecting the time the entry was created, e.g., "1550633367665"). Unfortunately, I encounter difficulties progressing beyond this point.

To elaborate further on how this modelis created, below is the related code section:

ListPage {
    id: adminPage

    model: Object.keys(adminModel)

delegate: SwipeOptionsContainer {
    id: container

    rightOption:  SwipeButton {
        anchors.fill: parent
        backgroundColor: "red"
        icon: IconType.trash

        onClicked: {
            container.hideOptions()
        }
    }

    SimpleRow {
        id: userRow
        width: parent.width
        text: modelData
        }
    }
}

Presenting My Question:

How can I construct a listView with delegates representing any object containing a "status" : "pending"? While similar implementation has been carried out using a loop such as

if (value[i].status === pending) { arr.push({...})}
, the challenge arises when dealing with an unknown subgroup (Stylist/Administrator). In other words, although the database example comprises only two list elements, there could potentially be numerous more with varied subGroup scenarios.

Answer №1

Once you have retrieved the data using getValue from FireBase, it appears that there are a few steps to follow:

  1. Get the subgroups within your group.
  2. Iterate through each subgroup.
  3. Retrieve the time entries for each subgroup.
  4. Filter the time entries based on the status being "pending".

It seems like you have already completed Step 1 by using Object.keys(adminModel). Now, we can move forward with a for-loop (Step 2 √).

var subgroups = Object.keys(adminModel);
for (var i in subgroups) {
    var subgroup = adminModel[subgroups[i]];

    // ...
}

For easier access, a variable called subgroup_obj has been defined to store subgroup data. For instance,

"Stylist": {
      "1551222170677" : {
           "date" : "2019-02-19T12:00:00.000",
           "details" : "Full Day",
           "name" : "Stylist Stylist",
           "status" : "pending"
      }
}

Next, we proceed to Step 3 by fetching time entries using Object.keys() on the subgroup.

var timeEntries = Object.keys(subgroup);

With Step 4, we can filter the entries with a pending status by employing the filter() array method.

var filteredEntries = timeEntries.filter(function(t) { return subgroup[t].status === "pending"; } );

Although a newer version of JS allows

timeEntries.filter(t => subgroup[t].status === "pending")
, this may not be fully supported by Qt yet.

After these steps, filteredEntries will provide an array of time entries (e.g. [ "1551222170677" ]) for each subgroup.

If you require the complete time entry object, you can utilize the map array method to achieve

var filteredEntries2 = filteredEntries.map(function(t) { return subgroup[t]; });

resulting in an array of objects. For example,

[
{
    date: "2019-02-19T12:00:00.000"
    details: "Full Day"
    name: "Stylist Stylist"
    status: "pending"
}
]

I hope this explanation proves helpful!

Answer №2

Retrieving data from the Firebase Database results in receiving a DataSnapshot object that includes a forEach method for iterating through child nodes.

To load a group and display the names of all items:

firebase.database().ref("group").once("value").then(function(snapshot) {
  snapshot.forEach(function(groupSnapshot) {
    groupSnapshot.forEach(function(subgroupSnapshot) {
      console.log(subgroupSnapshot.val().name);
    })
  })
})

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

Unable to utilize static files in node.js and express

Attempting to utilize node.js and express for crafting a chat client has proven to be a bit challenging. Whenever I attempt to incorporate external CSS or JS files, I encounter GET errors. My current configuration in index.js is as follows: var express = ...

Run the command "node index.js" to simultaneously start and stop the server

After installing WSL2 and the Ubuntu 22.04 distribution on Windows 11, I set up my environment, installed nvm, Node version 16.17.1, and then ran npm init in my folder. Following that, I installed Express and created an index.js file with a simple structur ...

What is the process for pausing a video while it is still buffering and loading?

Is it possible to suspend a video when it is in an opening or preparing state? For example, if I open a video and then switch to another application using the smart hub feature, how can I suspend the video while it is in the process of opening or preparin ...

What is the best way to handle invalid JSON when using json_decode()?

sample.php {"status": "yes"} {"status": "no"} output: yes , no I am encountering an issue with my website displaying a blank page(Using the code provided), can you offer any assistance in resolving it? <?php $da ...

Calculate the overall length of a specified time interval using Node Js

My task involves calculating overtime based on work start and end times. We are looking to calculate overtime hours that fall outside of the regular work schedule. For example, the regular work timings are from 10:00 AM to 07:00 PM Overtime needs to be ...

Issue with Iframe DOM: encountering undefined values while attempting to retrieve form field data

For some reason, I've been struggling to debug a piece of JavaScript that should be straightforward. I've experimented with various approaches, such as using a form to access fields and using getElementById. I've also played around with incl ...

Utilizing Ajax to dynamically generate unique ID's for multiple checkboxes

I have been working on a website that is almost completed, however, I have come across a new task where I need to select check-boxes in order to archive news items or "blog posts". The concept is to have a check-box next to each blog post and by checking ...

Modify the `<link>` tag using the `onclick` function in JavaScript

I want to switch up the site's style with just a click on an icon <head> <meta charset="utf-8"> <link rel="stylesheet" href="styled.css" id="styles"> </head> Everytime I try to tackle th ...

Issue encountered while utilizing PHP sessions

I'm currently developing a basic login page that utilizes JS, JQuery, and PHP. login.php <!DOCTYPE html> <head> <title>AJAX Login Learning Activity</title> <link rel="stylesheet" type="text/css" href="login.css"> ...

Employing plain Javascript (without the use of jQuery) to concatenate information from two JSON strings - encountering an error due to the absence of

Having a JSON stringified form data like this: {"name":"jack miller", "address":"123 main st"} I aimed to append more records but encountered an error saying "append is not a function." The desired outcome is to have both sets of records in this format: ...

Enhance Image Size with a Custom React Hook

I've created a function to resize user-uploaded images stored in state before sending them to the backend. const [file, setFile] = useState(null) function dataURLtoFile(dataurl, filename) { let arr = dataurl.split(','), mime = arr[0].ma ...

Retrieve all existing Session Variables that start with a specific prefix

Hey everyone, I have set up a series of session variables using an id as part of the name. For example, I have these variables: $_SESSION['test_variable_1']; $_SESSION['test_variable_2']; $_SESSION['test_variable_3']; I&apos ...

What is the best way to show instructions immediately upon receipt of a response?

I'm currently working on developing a website similar to ChatGpt using the OpenAI API for GPT. However, there is a delay in generating responses with GPT taking a few seconds. As a result, my code only displays the instruction once the response from G ...

Can Angular 5 integrate with Pusher?

Below is the javascript code used to integrate Pusher into native HTML: <head> <title>Pusher Test</title> <script src="https://js.pusher.com/4.1/pusher.min.js"></script> <script> // Enable pusher logging - don't i ...

Get rid of the folder from the URL using an <a> tag

I have both an English and French version of my website located at: *website.com/fr/index.php *website.com/index.php Currently, I have a direct link to switch between the two versions: -website.com/fr/index.php -website.com/index.php. However, I ...

Using Element as a type parameter in a React/Typescript function

In my React project using Typescript, I am working on creating a generic collection. The current setup is as follows: class List<T> { constructor(data: any){...} } This code allows me to create a list of a specific type. My goal is to perform a ...

What is the best way to create a JavaScript array after fetching data from an AJAX request that returns a JSON array?

When I make an ajax call that returns JSON data, my goal is to extract and organize this data into a new JavaScript array through looping. This is a snippet of the JSON data returned: { query: [ ], products: 
[ 
{ title: "title 1", ...

How do I access a specific child from an object/element retrieved by using the elementFromPoint() method in Javascript?

Is there a method to extract the child element from an element or object retrieved by the function elementFromPoint(x, y); Consider the following scenario: var elem = document.elementFromPoint(x, y); Let's assume that the element returned and saved ...

A step-by-step guide on integrating associations from json files using sequelize-fixtures

Greetings everyone, I am new to sequelizejs and currently exploring its functionality. I am encountering difficulties in creating example datasets using sequelize-fixtures. This is how my models are set up: User.js (without beforeCreate, beforeUpdate ho ...

Access the data stored within a nested JSON key

Currently, I am making a request to the LinkedIn API in order to fetch profile data and it returns a JSON response. { "firstName": "Cristian Viorel", "headline": ".NET Developer", "location": { "country": {"code": "dk"}, "name": "Northern Re ...