3

I am trying to loop an array levels using Vue.js, I could to get the response json in actions with function forEach like:

  let filters = []
            const array = response.data
            array.forEach((element) => {
               filters.push(element)
            })
        

then stored data in state, there any way to filter by TYPE and then loop Data somehow to render in a select, data...etc. using V-for in Vue.js?

My json file:

     [
  {
    'type': 'filter',
    'datatype': 'str',
    'data': [
      {
        'var_name': 'Gender',
        'options': [
          'Male',
          'Female'
        ]
      }
    ]
  },
    {
      'type': 'filter',
      'datatype': 'date',
      'data': [
        {
          'var_name': 'From',
          'options': []
        }
      ]
    },
    {
      'type': 'range',
      'datatype': 'date',
      'data': [
        {
          'var_name': 'From',
          'options': []
        },
        {
          'var_name': 'To',
          'options': []
        }
      ]
    }
  ]

2 Answers 2

7
<div v-for="filter in filters">... </div>
computed: {
    filters() {
        return this.data.filter(item => item.type === 'filter')
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use below code in .vue file.

  1. save your above filters array to data variable in vue file.

    data() {
       return {
          filters: []
       }
    }
    
    const array = response.data;
    
    array.forEach((element) => {
       this.filters.push(element);
    })
    
  2. and in html template use v-for like below.

    <template v-for="oneItem in filters.filter(item => {item.type == 'filter'})"> 
    </template>
    

1 Comment

I would suggest wrapping this filtered list inside a computed property, they are cached which will make your code faster as long as you don't change the original list.

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.