user2410266
user2410266

Reputation: 551

vue.js - How to split array of objects and display in two different columns

I have two columns with name and age.The jason returns the following object.I would to return the value under name and age column.

 Students: {
  details: [
   { John: 21 },
   { Brian: 22 },
   { Ryan: 21 },

     <tbody>
        <tr v-for= "(item,index) in Students.details" :key="index" >
          <td ">
            {{item --(should display name)}}
          </td>
          <td">
            {{item --(should display age)}}
          </td >
        </tr>
      </tbody>

Upvotes: 1

Views: 1130

Answers (2)

ecoplaneteer
ecoplaneteer

Reputation: 1984

This could work out:

<tbody>
        <tr v-for= "(item, index) in Students.details" :key="index" >
          <td>
            {{Object.keys(item)[0]}}
          </td>
          <td>
            {{item[Object.keys(item)[0]]}}
          </td >
        </tr>
</tbody>

Upvotes: 1

kevinluo201
kevinluo201

Reputation: 1663

There are many ways to solve your problem, but I suggest to arrange the data first to a simpler form then render them. For example, use computed to change the form first.

computed: {
  dataArray() {
    return Object.keys(this.Students).map(name => {
        return {
          name: name,
          age: this.Students[name]
        }
    })
  }
}
// you can get an array [{name: "John", age: 21}, {name: "Brian", age: 22}, ...]

Then in the template just show the data:

<tr v-for= "item in dataArray" :key="item.name">
  <td>
  {{ item.name }}
  </td>
  <td>
  {{ item.age }}
  </td >
</tr>

Upvotes: 0

Related Questions