Home > other >  Vue js array dynamic loop
Vue js array dynamic loop

Time:06-08

Im having two arrays : days:[0,1,2,3,4,5,6] and wdays:[2,3,6]

I want to loop through both the array and the output must be as follows :

  • 0 : not present
  • 1 : not present
  • 2 : present
  • 3 : present
  • 4 : not present etc...

and the code must be in vue.js

CodePudding user response:

Maybe something like following snippet:

new Vue({
  el: "#demo",
  data() {
    return {
      days:[0,1,2,3,4,5,6],
      wdays:[2,3,6]
    }
  },
  computed: {
    items() {
      return this.days.map(d => {
        return this.wdays.includes(d) ? {[d]: 'present'} : {[d]: 'not present'}
      })
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <li v-for="(item, index) in items">
    {{ Object.keys(item)[0]  }}: {{ Object.values(item)[0] }}
  </li>
</div>

CodePudding user response:

the code must be in vue.js - I think it should me more of logic to check the values of one array into an another array.

You can simply achieve that by using Array.map() along with Array.includes() method with the help of ternary operator.

const days = [0,1,2,3,4,5,6];

const wdays = [2,3,6];

const res = days.map(item => {
    return !wdays.includes(item) ? 'Not present' : 'Present'
});

console.log(res);

  • Related