Home > Back-end >  Is it problematic to use a user ID as an array index when looping in VueJS where multiple points of
Is it problematic to use a user ID as an array index when looping in VueJS where multiple points of

Time:12-07

A couple of times, I've designed systems where I need multiple inputs generated in a loop, which will take data stored against that entity's records. Hence, I use the entity's ID as an array key for the referencing.

In example:

<table>
    ...
    <tbody>
        <tr v-for="member in employees">
            <td>@{{ member.name }}</td>
            <td>@{{ member.email }}</td>
            <td>
                <input type="text" v-model="emp_codes[member.id]" />
            </td>
            <td>
                <input type="text" v-model="emp_cats[member.id]" />
            </td>
        </tr>
    </tbody>
</table>

This creates arrays with user ID indexes ([member.id]). This works, but I could see issues arising from this over time & database growth (large IDs as array index causing memory issues in browsers?).

It seems hacky, I'd like to know if there's a better way. Thanks!

CodePudding user response:

You can use Map instead. The Map object allows you to store key-value pairs, where the key can be any value (including an object or a large number), and the value can be any data type.

declare your variables in data something like this:

data() {
    return {
        emp_codes: new Map(),
        emp_cats: new Map()
    }
}

And, use them in your template like this:

<input type="text" :value="emp_codes.get(member.id)" @input="emp_codes.set(member.id, $event.target.value)" />
  • Related