Search code examples
vue.jsv-for

v-for treat single object the same as collection of objects


I have an object (let's call it employments) like

{
 StartDate: "2018-01-01",
 Name: "Chris"
}

Sometimes employments will be a collection of objects like:

{
 StartDate: "2018-01-01",
 Name: "Chris"
},
{
 StartDate: "2017-01-01",
 Name: "Adam Brown"
}

If I iterate like this

<div v-for="employment in employments">
    <p>{{employment.StartDate}}</p>
    <p>{{employment.Name}}</p>
</div>

The keys given (e.g. employment.StartDate) in the first object example will fail because the v-for will iterate through the keys of the object instead of the object as a whole. The second collection of objects will work correctly.

How can I force v-for to treat both objects given in the example the same?


Solution

  • You can't force v-for to treat an object as an array; You need to convert your data to proper format before iterating through it; A type check could be an option:

    v-for="employment in (Array.isArray(employments) ? employments : [employments])"