0

I have data in this form:

itemlist : {
  "dates": [
    "2019-03-15", 
    "2019-04-01", 
    "2019-05-15"
  ], 
  "id": [
    "arn21", 
    "3sa4a", 
    "wqa99"
  ], 
  "price": [
    22, 
    10, 
    31
  ]
}

I want to use v-for in my created component that loops through this object treating every index in those 3 nested arrays as one observation. So dates[0], id[0] and price[0]correspond to same item, dates[1] id[1] price[1] is second and so on.

So In other words I think I need to transform this into, but not sure:

0 : {
dates: "2019-03-15", 
id: "arn21", 
price: 22,}
1:{
dates: "2019-04-01", 
id: "3sa4a", 
price: 10}
}
2:...

Thats how I pass the data to the component:

<tempc v-for="i in itemlist" :key="i.id" :price="i.price" :dates="i.dates"></temp>

But this does not work for the original data

1 Answer 1

3

You can create a computed property for this:

Vue.component('my-component', {
  template: '#my-component',
  data() {
    return {
      itemlist: {
        "dates": [
          "2019-03-15",
          "2019-04-01",
          "2019-05-15"
        ],
        "id": [
          "arn21",
          "3sa4a",
          "wqa99"
        ],
        "price": [
          22,
          10,
          31
        ]
      }
    };
  },
  computed: {
    // Note: here I assume these arrays will always have the same length
    mergedList() {
      return this.itemlist.dates.map((dates, i) => {
        return {
          dates,
          id: this.itemlist.id[i],
          price: this.itemlist.price[i]
        };
      });
    }
  }
});

var vm = new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.21/vue.min.js"></script>

<div id="app">
  <my-component></my-component>
</div>

<template id="my-component">
  <ul>
    <li v-for="i in mergedList" :key="i.id" :price="i.price" :dates="i.dates">
      {{i.id}} - ${{i.price}} ({{i.dates}})
    </li>
  </ul>
</template>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.