Trying to iterate through and make changes to a Firebase array results in an undefined

Update: Upon further investigation, it appears that value[i].extrainfoimage is only undefined when accessing imageRef.child("-JlSvEAw......

Despite reviewing the documentation multiple times, I still haven't been able to resolve this issue.

Essentially, I fetch data from Firebase and store it in an array. Then, I loop through that array and aim to update certain properties with data retrieved from other locations within my Firebase database. However, every time I attempt to update these properties, I encounter

"Uncaught TypeError: Cannot set property 'extrainfoimage' of undefined"

Here is the code snippet:

var questionsRef = new Firebase("https://XX.firebaseio.com/Questions");
var imageRef = new Firebase("https://XX.firebaseio.com/Images");

// Retrieve the first 6 items
var query = questionsRef.orderByChild('date_time_asked').limitToFirst(6);
// Fetch them as a Firebase array promise
$scope.questions = $firebaseArray(query);
// Wait for the data to load
$scope.questions.$loaded().then(function (value) {
// Iterate through the array
for (i = 0; i < value.length; i++) {
    // Check if there is data to be replaced
    if (value[i].extrainfoimage) {
           // If there is, fetch it from Firebase and replace the property
           imageRef.child("-JlSvEAwu5-WZJkOE_b/image").once("value",function(data){
                        value[i].extrainfoimage = data.val();
                    });
                }
            }
        })

Answer №1

It could be due to the absence of extrainfoimage in the last item of the value. Because your asynchronous setting for value[i].extrainfoimage doesn't correctly capture the value of i, it fails during execution.

Consider enclosing it in an IIFE:

for (i = 0; i < value.length; i++) {
    //check if there is data to be replaced
    if (value[i].extrainfoimage) {
       (function(curr) {
           //if there is data, fetch it from firebase and replace
           imageRef.child("-JlSvEAwu5-WZJkOE_b/image").once("value", function(data){
                    value[curr].extrainfoimage = data.val();
           });
        })(i);
    }
}

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

Updating the $location variable from the $rootScope perspective

I am facing an issue with my web app which is built using AngularJS. I have two functions in my code - one declared on the $rootScope and the other on the $scope. The code snippets are shown below: app.js app.run(function ($rootScope, $location) { $roo ...

Is it possible to use a += operator with attr() and val() functions in JavaScript?

Ever since I switched to jQuery, my development process has significantly sped up. However, there is one task that has become a bit more time-consuming: appending a string to an attribute or value. For instance, if you wanted to add a letter to the value ...

Leveraging Angular to dynamically adjust the height of ng-if child elements based on parent

I'm struggling with a few things in my current setup. I have a view that consists of 3 states - intro, loading, and completed. My goal is to create a sliding animation from left to right as the user moves through these states. Here is the basic struc ...

JS Issue with Generating Content

Introduction( kind of :) ) Starting with the process of generating 5 coffee beans for each cup of coffee. The coffee class includes a strength attribute, and my goal is to visually distinguish the coffee beans which have a strength greater than the select ...

The input box refuses to accept any typed characters

I encountered a strange issue where the input box in the HTML was not allowing me to type anything. const para = document.createElement('p') const innerCard = document.getElementsByClassName('attach') for(let i = 0; i < innerCard.l ...

What could be causing the issue preventing me from updating an npm library to the latest version and keeping me stuck with an older version?

Currently, I am using Node v14.16.1 and npm 7.9.0 I'm trying to update the Firebase-tools library by running either sudo npm upgrade firebase-tools -g or sudo npm install -g firebase-tools to ensure that I have the latest version of firebase-tools. ...

The jQuery date picker is showing an error with the function daySettings[2].replace, indicating that

Encountering a problem with the jQuery version I am using: <script src="js/Common/jquery-2.1.1.min.js" type="text/javascript"></script> <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script> The code I have writte ...

How can you save the output of console.log in JavaScript to a variable and then use that variable in HTML?

Here is the code snippet I've been working on. The first part consists of JavaScript code, and the second part includes HTML. $('#table').on('check.bs.table', function (e, row) { checkedRows.push({First: row.fname, Second: row ...

How do I hide a dropdown menu when the selector's value changes in iOS6?

I'm currently developing a hybrid application using Worklight. When I tap on a select control, a native dropdown appears. However, when I choose an option and the onchange event is triggered, the dropdown doesn't disappear unless I tap on the do ...

I am facing issues with jQuery's live and livequery functions when trying to use them with a form that is being loaded dynamically through

Previously, I inquired about a related issue regarding attaching behavior to an element with jQuery after insertion. However, I have not yet found a solution. For clarity's sake, I am posing a new question with a different scenario. Below is the code ...

Tips for filling a Rails dropdown list using a JSON array

My Ant show page showcases detailed information about different types of ants. There are two drop downs on the page - one for environment: [indoor, outdoor], and another for diet: [sugar, fat, protein]. When a parameter is selected from each dropdown, it ...

The TypeScript error states that the argument type 'string | undefined' cannot be assigned to the parameter type 'string'

Receiving TS error that says "Object is undefined" I am attempting to retrieve the "userid" from my headers. However, I keep encountering the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'str ...

Utilizing the power of JavaScript, CSS, and HTML to seamlessly transfer selected items from one webpage to the shopping cart displayed on another page

Due to limitations on using back-end code, I'm seeking advice on how to implement this function. Most tutorials I've come across show the items and shopping cart on the same page. I've heard suggestions about using Jquery.load(), but I&apos ...

Using Javascript to dynamically add rows to a table, however they mysteriously appear and disappear soon

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UserPermisson.aspx.cs" Inherits="TestProjects.UserPermisson" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" ...

Using TypeScript, extract the value of a Promise from a Page Object

Struggling to retrieve a value from a WebDriver promise in a Protractor solution using TypeScript, the response keeps coming back as undefined. get nameInput(): string { var value: string; this.nameElement.getAttribute('value').then(v =& ...

Display a div beside it when hovering over a specific part of the image

If I have an image that is 200px wide and 900px tall How can I make a div display alongside it when hovering over a specific section of the image? ...

Each styled component will yield the respective type definitions using (@types/styled-components)

Encountering a strange problem with styled-components in VSCode. Every component from styled-components is returning 'any'. https://i.sstatic.net/0kFJw.png https://i.sstatic.net/S20cS.png I had it working previously, but unsure when it stopped ...

Preventing the Sending of Origin Header in Angular 2

I am facing an issue in my Angular2 project where the HTTP service is automatically adding the 'Origin' header with a value to all of the requests. Is there a way to stop Angular2 from including this 'Origin' header in the HTTP calls? A ...

jQuery smoothly sliding downward from the top to the bottom

http://jsfiddle.net/Hx65Q/3/ Is there a way to make the slider open from the top instead of the left side? $("button" ).click(function() { $('.login').toggle('slide', { duration: 1000, easing: 'easeOutBounce', }); ...

One of the functionalities is not functioning properly: either the validation or the AJAX

My validation code was working fine until I added some ajax code. Now, when I include the onclick="return chk()" in the submit input field, the validation code stops working. But if I remove it, the ajax code doesn't work. How can I resolve this issue ...