Reputation: 736
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
Upvotes: 2
Views: 3305
Reputation: 11824
return Object.keys(this.list)
.filter(key => this.list[key] === true)
.map(x => { return {'name': x, 'active': this.list[x]} });
https://jsfiddle.net/fowz746b/
Upvotes: 2
Reputation: 349
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>
Upvotes: 0
Reputation: 101
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).
Upvotes: 0