[Vuejs]-Vue accessing an array within in an array

3👍

Ah yep, don’t do that with v-for. Create yourself some computed properties and use Array.filter(), then in your template, point the computed property.

computed: {
    selectedSpaceObj() {
        return this.spaces.filter(aSpace => aSpace.id === this.selectedSpace)
    },
    selectedRoomObj() {
        return this.selectedSpaceObj.rooms
            .filter(aRoom => aRoom.id === this.selectedRoom)                
    }
}

Do it all in javascript. It will lead to much more readable code, and you will likely reuse the computed property all over the place. For selectedRoomObj, for example, we can just reuse the computed selectedSpaceObj.

Next, for code readability, and to avoid long accessors, create yourself space and room components. Nested v-for loops is a sure sign that you need them.

The problems you encounter might lead you to rethink the structure of your data. Perhaps you want to store selected as a property directly on the room and space objects? Perhaps it makes more sense to have 1 root level rooms array, with a “foreign key” into spaces?

Leave a comment