Gautam Menariya
Gautam Menariya

Reputation: 596

Vue 3 access object property by variable name

I am passing this from the parent as a prop

table_fields: [
    {label: 'Var 1', field: 'var_1'},
    {label: 'Var 2', field: 'var_2'},
    {label: 'Var 3', field: 'var_3'},
    {label: 'Var 4', field: 'var_4'},
    {label: 'Var 5', field: 'var_5'},
],

in the child component I am doing this

<table id="companiesList" class="table table-sm table-stripedd table-borderless table-hover table-responsivev">
    <thead>
        <tr>
            <th data-type="text" v-for="tableField in tableFields"  :key="tableField">{{tableField.label}}</th>
        </tr>
    </thead>
    <tbody v-if="date_loaded">
        <tr  v-for="single in data.data" :key="single.DUNS">
            <td v-for="tableField in tableFields" :key="tableField">{{single.tableField.label}}</td>
        </tr>
    </tbody>
    <tbody v-else>
        <tr>
            <td colspan="12" class="text-center">Loading...</td>
        </tr>
    </tbody>
</table>

Here I am getting data from an API call.

The table header is as expected, but not sure how to get value from API data in the loop.

I tried this:

{{single.tableField.label}} : Cannot read property 'label' of undefined

{{single.{{tableField.label}}}} : Parsing error

Wat I want is to get data which is like {{single.var_1}}

How to achieve this? Thanks in advance

Upvotes: 3

Views: 4465

Answers (1)

Dan
Dan

Reputation: 63119

Use bracket notation to access a variable property name of single, otherwise the code looks for a property whose name is the string tableField, which doesn't exist:

<td v-for="tableField in tableFields" :key="tableField.label">
  {{ single[tableField.label] }}
</td>

When using dot notation, the segments are taken as literal property names. when using bracket notation, the expression inside the brackets is evaluated for the property name.

Upvotes: 2

Related Questions