Home > front end >  filter data through computed property in vue
filter data through computed property in vue

Time:01-08

I have tried to add filter in computed property for object. and expecting the listing of object.

I have filtered data correctly but unable to create an array of object from computed property.

if you could help me on this that would be appreciated.

<div id="app">
  <div v-if="activeItems && activeItems.length > 0">
  {{ activeItems }}
      <ul>
        <li v-for="item in activeItems" :key="item.id">
          {{item.name}}
        </li>
      </ul>
  </div>
</div>

new Vue({
    el: '#app',
  data() {
    return {
        list: {
      "john" : true,
      "jane" : true,
      "lucy" : false
      },
      
    };
  },
  computed: {
    activeItems() {  
    return Object.keys(this.list)
             .filter(key => this.list[key] === true)
    /** expected 
      return `this.list` as an Array of object and filter by if active is true
          Expected output
          [
            {name: 'John', active: true},
            {name: 'Jane', active: true}
          ]
    **/
    
             
    }
  },
  mounted(){
    console.log(this.list);
  }
});

you can help on this link though https://jsfiddle.net/jakhodeM/we8t572z/6/

Thanks

CodePudding user response:

return Object.keys(this.list)
        .filter(key => this.list[key] === true)
        .map(x => { return {'name': x, 'active': this.list[x]} });

https://jsfiddle.net/fowz746b/

CodePudding user response:

Update your template string by removing the .name property.

        <li v-for="item in activeItems" :key="item.id">
          {{item}}
        </li>

It doesn't make sense to add an active status to activeItems (as they are always active).

CodePudding user response:

Here is the solution to your query.

 <template>
    <div id="app">
        <div v-if="activeItems && activeItems.length > 0">
            {{ activeItems }}
            <ul>
                <li v-for="item in activeItems" :key="item.id">
                    {{item.name}}
                </li>
            </ul>
        </div>
    </div>
</template>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                list: {
                    "john": true,
                    "jane": true,
                    "lucy": false
                },

            };
        },
        computed: {
            activeItems() {
                var arr=[];
                for (let key of Object.keys(this.list)) {
                    if (this.list[key]) {
                        arr.push({name: key, active: true})
                    }
                }
                return arr;
            }
        },
        mounted() {
            console.log(this.list);
        }
    });
</script>
  •  Tags:  
  • Related