[Vuejs]-Looping through emitted data?

0👍

Your users data as shown is an object, not an array, so it does not have a forEach method.

The object does contain two arrays inside it, names and addresses. Perhaps you meant to iterate through those arrays? Assuming that this.users is a valid reference to your users object, you could do:

this.users.names.forEach( function( name ) {
    // Do stuff with name
});

this.users.addresses.forEach( function( address ) {
    // Do stuff with address
});

Are users.names and users.addresses in a 1:1 correspondence, where users.names[0] and users.addresses[0] are both for the same user, and so on for [1], [2], etc.? In that case you could use:

this.users.names.forEach( ( name, i ) => {
    let address = this.users.addresses[i];
    // Do stuff with name and address
});

I used an arrow function here instead of a regular function to preserve this.

However, if the names and addresses arrays are in a 1:1 correspondence like this, I would recommend restructuring the users data if you are able to do that.

Instead of users being an object containing two parallel arrays, make users be the array, where each element of this array contains a name and address property. This way all the data for a user is grouped together for easy access. This will be especially helpful if you add other user fields such as phone or email:

let users = [
    {
        "name": "Mike",
        "address": "California",
        "phone": "510-555-0001",
        "email": "mike@example.com"
    },
    {
        "name": "Panthro",
        "address": "Oregon",
        "phone": "510-555-0002",
        "email": "panthro@example.com"
    }
];

users.forEach( function( user ) {
    console.log( user.name, user.address, user.phone, user.email );
});

As you can see, this way of structuring your user data makes it easy to access the individual data fields for each user.

Leave a comment