JustStartedProgramming
JustStartedProgramming

Reputation: 327

How to traverse through Dynamic Object of Arrays in VueJS

I have an object with arrays which is nothing but JSON reply from server which I converted into Object and now it looks like this (but lot of values into it):-

Object_return:{
       name:[1,25,2,24,3,78],
       age:[2,34,4,78]
      }

here name and age is dynamic coming from the server, so I do not know what exact values coming there so I can not refer it while iterating through the for loop

<th v-for = "item in Object_return.name">

and also I want to show this in a DataTable so the first row should looks like this

         ------------------
                  1 25
                 -------
         name     2 24
                 -------
                  3 78
     --------------------

second row

    ---------------------
                  2 34
                 -------
         age      4 78
      ------------------------

and so on and so forth for all the values coming from the server

Does someone have an idea how to do this

Upvotes: 2

Views: 577

Answers (1)

Bert
Bert

Reputation: 82459

You can iterate over an object and get the key value as the second argument.

<tr v-for="val, key in Object_return">

Here, key will be the name of the property.

Then, since you want to group the arrays in pairs, I suggest a computed property to massage the data into the format you want.

Here is a working example.

console.clear()

new Vue({
  el: "#app",
  data:{
    serverData: {
       name:[1,25,2,24,3,78],
       age:[2,34,4,78]
      }
  },
  computed:{
    massaged(){
      return Object.keys(this.serverData).reduce((acc, val) => {
        // split each array into pairs
        const copy = [...this.serverData[val]]
        let pairs = []
        while (copy.length > 0)
          pairs.push(copy.splice(0, 2))
        // add the paired array to the return object  
        acc[val] = pairs
        return acc
      }, {})
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
  <table>
    <tr v-for="val, key in massaged">
      <td>{{key}}</td>
      <td>
        <table>
          <tr v-for="pair in val">
            <td>{{pair[0]}}</td>
            <td>{{pair[1]}}</td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</div>

Upvotes: 2

Related Questions