VueJS resets numeric keys

Posted 11 months ago by robjbrain

I have a dynamic form that can have multiple fields. Not all fields necessarily appear on a form but I still want to access them. In PHP it would look something like this:

$fields = [
    1 => $fieldObject1,
    2 => $fieldObject2,
    3 => $fieldObject3,
    4 => $fieldObject4,
    5 => $fieldObject5,
    6 => $fieldObject6,

$form = [
    'name' => 'My Form',
    'fields' => [1,2,4,6]

foreach($form->fields as $field_id) {
    echo $fields[$field_id]->renderHtml();

Or something like that (realistically I would probably use a collection or something, but this was a simpler example).

However when I return $fields and $form from Laravel into a VueJS component, the id's are not retained and it looks like this:

fields: Array[6]
    0: Object,
    1: Object,
    2: Object,
    3: Object,
    4: Object,
    5: Object

<div v-for="field_id in form.fields">
    // Just an example, this is not what i'm actually doing
    // This would return undefined once I got to 6 and would show incorrect elements for the other
    {{ fields[field_id].html }}

The numerical ID's are reset to an incremental 0,1,2,3,4,5 etc so 6 would be undefined.

What's the proper way to handle this in JS/VueJS?

Please sign in or create an account to participate in this conversation.