What is the best way to add my sub-objects into an array?

When retrieving data from Firebase, the output is in the form of objects:

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

Displaying these objects using Ng-Repeat is easy, but when trying to search through them with an input field and filter, an error occurs because it expects an array instead of objects.

To resolve this issue, I converted the objects into an array like so:

var userId = firebase.auth().currentUser.uid;
var ref = firebase.database().ref('/accounts/' + userId + "/cards/");

var cards2 = [];
ref.orderByChild('cards').on("value", function(snapshot1) {
  var cards1 = snapshot1.val();
  cards2.push(cards1);
  console.log(snapshot1.val());
  $timeout(function(){
  $scope.cards = cards2;
  console.log(cards2);
  })
})

The resulting output looks like this: https://i.sstatic.net/V2mGI.png

In essence, my ng-repeat cannot display properly because the objects are nested as sub-objects within the array!

How can I separate them to enable displaying them correctly within ng-repeat and also be able to filter them using the following code:

ng-repeat="card in cards | filter:searchText"

EDIT : here is my HTML code :

<ion-view view-title="MY CARDS">
    <ion-nav-buttons side="right">
        <button class="button button-icon icon ion-android-more-vertical"></button>
    </ion-nav-buttons>
    <ion-content class="padding">
     <div class="list list-inset input-search">
            <label class="item item-input">
                <i class="icon ion-search placeholder-icon"></i>

                <input ng-model="searchText" type="text" placeholder="Search">
          </label>
        </div>
        <a><div  ng-click="toUserView($index)" value="Taba" ng-repeat="card in cards | filter:searchText" class="list card ">
            <div class="item item-avatar item-icon-right">
                <img ng-src="{{card.photoURL}}">
                <h2>{{card.name}}</h2>

                <p class="icon-p">
                    {{card.description}}
                </p>
                <p style="color:white;" id="rotaryId{{$index}}" >{{card.rotaryId}}</p>
            </div>


        </div></a>

    </ion-content>
</ion-view>

Answer №1

Consider using the following code snippet:

 var userId = firebase.auth().currentUser.uid;
 var ref = firebase.database().ref('/accounts/' + userId + "/cards/");

 var cardsList = []; // Initialize an empty array to store the cards
  ref.orderByChild('cards').on("value", function(snapshot) {
       var cardsData = snapshot.val(); // Get the data snapshot
       for(var key in cardsData){
          cardsList.push(cardsData[key]); // Push each card object into the array
        }
        $scope.cards = cardsList; // Update scope variable with the list of cards
        console.log(cardsList); // Log the array of objects to the console
      });
    

This will result in an array of card objects

Answer №2

  1. It is recommended to avoid using arrays in Firebase as it does not store them directly. Check out this resource for best practices: Best Practices - Arrays in Firebase

  2. Instead of using ng-repeat with just the array, consider iterating over the object's keys as shown here: How can I iterate over the keys and values in ng-repeat in Angular

Replace:

ng-repeat="card in cards

with:

ng-repeat="(key, card) in cards

For instance:

<a><div  ng-click="toUserView($index)" value="Taba" ng-repeat="(key, card) in cards | filter:searchText" class="list card ">
    <div class="item item-avatar item-icon-right">
        <img ng-src="{{card.photoURL}}">
        <h2>{{card.name}}</h2>

        <!-- *class time / time and icon -->
                        <!-- *class icon-p / icon location -->
        <p class="icon-p">

            {{card.description}}
        </p>
        <p style="color:white;" id="rotaryId{{$index}}" >{{card.rotaryId}}</p>
    </div>


</div></a>

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

Understanding the scope of Javascript variables in mongoose queries

I am currently working on a project utilizing node.js, mongoose, and the Foursquare API. foursquare.getVenues(params, function(err, venues) { if(err) return res.json(JSON.stringify({status: 'error', returnData: err})); ...

Manipulating strings within strings with JavaScript

It's been a strange discovery I made while working with JavaScript. Whenever I try to assign a two-word string to a CSS property, like setting the fontFamily property of an HTML element to "Arial Black", it ends up looking something like thi ...

JavaScript: Determine the wild decimal value produced by subtracting two decimal numbers

In the process of creating a service price tracking bot, I encountered an issue with displaying price decreases. Here is an example of what it currently looks like: Service price decreased from 0.10 to 0.05 If you buy right now, you could save <x> ...

Creating Layouts with Bootstrap 3

I'm exploring the codepen below in an attempt to mimic the appearance of the image provided consistently across all screen sizes. However, there are two issues that I am encountering - firstly, the green numbers on the first line which represent the d ...

Contrasting {} and {} as any in TypeScript

Seeking clarity on TypeScript, what sets apart (foo and foo2) from (foo3 and foo4)? (foo and foo2) as well as (foo3 and foo4) produce identical results, yet during compilation, a red underline appears under foo2 and foo3. https://i.stack.imgur.com/lWaHc. ...

Using the Permissions directive in Angular

Currently, I am developing a Single Page Application (SPA) that interacts with a REST server on the backend. The objective is to create a user interface that is consistent across all roles. For example: On a product page, a guest can view the product and ...

ng-view or controller appears to be malfunctioning

I'm currently working on a small web application using AngularJS. I have an index.html file in the main directory and three other HTML pages within the html subdirectory. login.html list.html detail.html Initially, the index.html should load the ...

What is the correct way to pass parameters when using the setState() function in React hooks?

I am working on a project where I have a list of country names. When a user clicks on one of the countries, I want to update the state with the name of the newly selected country. This state change will then trigger other changes in a useEffect(). The stat ...

Obtaining Master-Detail table data via WebAPI

I have a scenario where I am working with a database that consists of two tables linked by a foreign key relationship, following the classic master-detail structure. My goal is to retrieve all the data from these tables using ASP.NET MVC WebAPI calls from ...

Using MVC4 and jQuery to unselect items from an Html.CheckboxListFor

In my search page, I am utilizing jQuery to toggle the visibility of different sections based on user input. Specifically, I have a Html.Textbox and Html.CheckboxListFor that are shown or hidden depending on whether there is any input in the textbox or if ...

Modifying an image or audio using document.getElementByID("...").src=x+".png" is not effective

I'm having trouble figuring out why it's not working. I've searched online and here, but all I could find were tutorials that didn't include the variable or questions that were too specific. Can someone help me with this? <html> ...

Ways to receive alerts when a marker enters a polygon

Looking for a way to receive notifications if my marker enters any of the polygons on the map. Having trouble implementing it correctly, here is my current code: <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com ...

Modify path and refresh display upon ajax call to node server

Recently, I made the decision to utilize a Node server as a proxy for making API calls to third-party public APIs from my front end. After successfully sending a request to my Node endpoint and then to the third-party API, I received the expected response. ...

React Js: Error encountered while parsing JSON due to an unexpected token < at the beginning

I am having issues fetching my JSON file in React JS using the fetch method. An error is popping up that says: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 I am unable to figure out what the error could be, even after va ...

Using Highcharts within a Vue.js component

I'm having trouble creating graphical components with Highcharts and Vue.js because I can't figure out how to dynamically set the id attribute that Highcharts needs to render properly. Does anyone know how to set the id dynamically? This is the ...

Tips on retrieving a result from mongoose's findOne() function

I created a custom function using the findOne() method in Mongoose and now I need to use the result for another function. How can this be achieved? Thank you! module.exports.retrieveDeal = function(dealRequest){ Deal.findOne({name:dealRequest},functi ...

What causes a globally declared array to remain empty in the global scope even after data is pushed to it within a callback function?

Initially, I set an empty array as the value for the global variable artistURLs. Then, within the Cheerio .each() iterator method, I push strings (stored in the local variable artistURL) into the artistURLs array. var request = require('request&apos ...

Tips for transferring the input text box value to angularjs when clicking on the text box

Here is the HTML code snippet: <tr ng-repeat="c in client"> <td><input type="text" id="id" value="{{c.id}}" onclick="display();"></input></td> <td><input type="text" value="{{c.fname}}"></td> </ ...

Is there a way to make the onKeyDown event function properly in Next.js/React?

I'm currently developing a website with Next.js and am facing an issue trying to execute a simple function when a key is pressed. Strangely, the onKeyDown event isn't getting triggered as expected in my code snippet: <main onKeyDown={e => c ...

Encountered an error while trying to retrieve data from

Having trouble with file uploads to the S3 bucket using @aws-sdk/client-s3 library and encountering errors when uploading files larger than 70kbps: `TypeError: Failed to fetch at FetchHttpHandler.handle (fetch-http-handler.js:56:13) at PutObjectCommand ...