I've been using this code repeatedly. I wonder if there is a more efficient way to create this shortcut
Take a look at the following example
// items.js
export default [
{ title: 'ABC', href: 'javascript:void(0)' },
{ title: 'DEF', href: 'javascript:void(0)' }
]
// index.vue
<script>
import items from './items.js'
export default: {
computed: {
links() {
let results = []
items.forEach((item,index) => {
item.id = index
results.push(item)
})
return results
}
}
}
</script>
//resulting object = {title: 'ABC', href: 'javascript:void(0)', id: 0}
I just want to add an id property to each object in the computed property, so that I don't have to worry about using
v-for="(item, index) in items" :key="index"
. Instead, I can use v-for="item in links" :key="item.id"
in the template
The question:
In the code, I declare an empty array called results
let results = []
, then populate it with data using forEach before returning the result. Is there a better way to return each looped data without declaring an empty array and populating it before returning the generated data?Sometimes I not only add an id, but maybe also other properties like
item.internal = true
, or levels if it's multilevel.