Search code examples
vue.jsv-for

Usage of v-for for looping through an array of objects in order to output a specific field's value


I have two objects/model:

export class AObject {
  public anumber: string;
}


export class BObject {
  public aObject: AObject[];
}

Inside my template, I would like to loop through an array of AObject[] and for each of them output the value for the property anumber. I have attempted at the following, but it is not working:

           <div class="fields fields-flex">
              <div class="field">
                <label>{{ $t('myLabel.aLabel') }}</label>
                <span v-for="(aObject) in aObjects" 
                  :key="aObject.number"> 
                  {{bObject.aObjects.number}}"</span>
              </div>
            </div>

Can you help?

Thanks!


Solution

  • If you have aObject[] as an array then your loop should look like

    <span v-for="aObjectInstance in aObject" 
     :key="aObjectInstance.anumber"> 
    </span>
    

    aObject is the name of the array, therefore aObject should be after in.

    Also, you should have v-for for going through all the BObject.aObject, you can't reference it like {{bObject.aObjects.number}}" because you don't have aObjects on BObject but aObject *.

    So that should look like:

    <span v-for="aObject in BObject.aObject" 
     :key="aObject.anumber">
     {{aObject.number}}"
    </span>
    

    I hope this helps.