A guide to organizing and storing an array of data within an array of objects in Firestore with the help of Vue.js

    uploadUsernames(){
      let currentUser = firebase.auth().currentUser
      db.collection('users').where('user_id',"==", currentUser.uid).get().then(snap => {
        snap.forEach((document) =>{
          for(let counter=0; counter<=this.usernames.length; counter++){
          db.collection('users').doc(document.id).update({
            name: this.name,
            bio: this.bio,
            usernamelist:[{Id:counter, username: this.usernames[counter]}]
          })}
        })
      }).then(() =>{
        this.$router.push({ name: "Profile" })
      })

I have a list of usernames stored in the 'usernames[]' array that I intend to save into my user documents. Each element's index corresponds to the 'Id' of every item within the Firestore document 'users', located in the 'usernamelist' field named 'username' at the matching 'Id'. How can I iterate through each array item and update the appropriate entry in Firestore? A message stating that 'i' is undefined is being returned as an error.

Answer №1

Welcome to our community!

It seems like you're working with arrays and iterating over them using indices. Just a heads up, when looping through an array with index values, remember to use "<" instead of "<=" to avoid going out of the index range:

for(i=0; i<this.usernames.length; i++)

Keep in mind that array indices start at 0, so the last index will be the length of the array minus 1.

Another thing to consider is handling asynchronous functions like update within a loop. It's recommended to create the entire field first and then update it with a single update statement to ensure proper execution.

I hope this information proves helpful for your project!

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

Splitting a JSON array into two separate arrays of values using jQuery: a step-by-step guide

My AJAX script is pulling a JSON array from a PHP file. Here's the script: // jsonData fetched from inc/wip-data.php var jsonData = $.ajax({ url: 'inc/wip-data.php', dataType: 'json', }); The JSON array looks like this: [ { ...

Adding JSON data to an array for Flot Diagram

I've been struggling with the task of organizing data into an array. The existing temp array is structured as follows: tmp[0][0] = "NY" tmp[0][1] = "52" tmp[1][0] = "FL" tmp[1][1] = "25" My goal is to transfer this data into a new array called data. ...

How can we ensure that the second function is executed only after the AJAX click method has finished in Javascript?

var err=0; $("#addsell").click(function(e) { e.preventDefault(); var data = { title: $('#title').val(), author: $("#author").val(), genre: $('#genre').val(), price: $('#price').val(), ad ...

Invoke JavaScript function upon page load

There is a link on my page that, when clicked, opens a login popup. However, I am struggling to make it work on page load. I have spent a lot of time trying to figure this out, but nothing seems to be working. <a id="onestepcheckout-login-link" href=" ...

When receiving a GET response after a server crash

Question: I am sending a Get request through Ajax every second and waiting for a response from the server. However, if my application crashes and I keep sending requests every second, I only receive a server timeout error (HTTP status code 502) with no oth ...

Trouble with basic AJAX form submission

I have created a basic form and AJAX function to send the form data. However, the data is not being posted as expected. Can someone assist in identifying the issue? Fiddle: https://jsfiddle.net/onyeLp4d/2/ HTML <div id="lp-pom-form-25"> ...

Generating unique names based on input from users

We are working with an array containing names and an input field where users can enter a string to receive name suggestions. The array includes names like Alex and Anna, and when the user types "a," we want to suggest these names. Below is the code snippet ...

Tips for changing images when hovering over them

Currently engaged in the development of an e-commerce application, where I am looking to accomplish a specific task... https://i.sstatic.net/sYoG8.png The objective is to display the corresponding large image on the big box when hovering over smaller ima ...

Exploring the efficiency of AngularJS when binding to deeply nested object properties

Are there any performance differences to consider when data binding in Angularjs between the following: <div>{{bar}}</div> and <div>{{foo.bar}}</div>? What about <div>{{foo.bar.baz.qux}}</div>? Our team is working o ...

When utilizing Angular 2, this message is triggered when a function is invoked from the Observable

One of my services is set up like this: @Injectable() export class DataService { constructor(protected url: string) { } private handleError(error: Response) { console.log(this.url); return Observable.throw(new AppError(error)); ...

In React, automatically scrolling to an anchor tag element using componentDidUpdate

My Website Link HTML Snippet <div className={parent}> <div className={child}> {someContent} <a id="api-doc">Hello API</a> </div> </div> I am developing the ...

regarding unfamiliar functions in code and their mysterious purposes

My journey learning Vue.js has been going well, but I've hit a roadblock. Can someone explain the meaning of _. in the following code snippet? ...

Identifying Whether Angular ng-repeat is Displaying Output or Not

I am trying to display a "No result" message when the search field does not have any matches. The current filter is working fine, but it does not show the message when there are no results. How can I achieve this? <div class="portfolio-list-wrap" ng-co ...

Difficulty with window.locationbar.visible in Internet Explorer 11

I am currently working on detecting popups in Selenium that do not display the location bar. In my code snippet, I am using JavascriptExecutor to retrieve the visibility of the location bar in Chrome by executing the script "return window.locationbar.visi ...

Removing information from the app.component.html file in Angular 6 and reflecting those updates in the view

I currently have a service that retrieves a list of data and displays it within the app.component.html. Below is the code snippet used to display the data: <ul> <li *ngFor="let data of retrieveData"> {{ data.id }} - {{data.title} ...

Filtering a user list array in JavaScript based on tags using regular expressions

I have a user list array that needs to be filtered by tags. I attempted to filter the array using the filter and match methods with a RegExp for matching the tag, but the results were not as expected. let users=[{id:1,name:'john',tags:' ...

inject a function into the navigation component

I'm seeking guidance on React Native navigation const Swipe = ({register}) => { const Stack= createStackNavigator() return( <NavigationContainer> <Stack.Navigator screenOptions= {{headerBackTitleStyle:{color:&a ...

Working with high-resolution images on HTML5 canvas

I am faced with a challenge of incorporating a 15000x15000 px vector image as the backdrop for my canvas project. It is essential to crop specific sections of this image swiftly and consistently, especially within requestAnimationFrame. My current method ...

Encountering an unexpected token in Javascript when using conditionals

I am currently attempting to integrate a JavaScript condition within a listed order, containing two radio buttons that need to be checked in order to progress to the following list based on the selection. <li data-input-trigger> <label class="fs- ...

Navigating asynchronous URL parsing in NodeJS

I am still fairly new to the world of Node.js and Javascript, so I appreciate your patience with my confusion around the callback mechanism Bacchanalia. The Issue at Hand I'm currently working on a basic Node.js application that is responsible for h ...