JoaoHamerski's avatar

Is it possible to use computed properties in array of objects?

For example, i have something like this:

data: () => {
	layers: [
		{name: 'Something', index: 0},
		{name: 'Something again', index: 1},
	]
}

I would like to add a computed property for every name property of my layers array, of course it will be the exctaly same function, i think it would be very useful in many cases but i have been searched and didn't find anything about that for Vue.

So i could call it like so: layers.name.computedName or something like that.

0 likes
2 replies
devingray_'s avatar
Level 8

You cannot use it like that layers.name.computedName But you can use filters

layers.name | customFilter

https://vuejs.org/v2/guide/filters.html

Example

data: () => {
	layers: {name: 'Something', index: 0},
},
filters: {
  capitalize: function (value) {
    if (!value) return ''
    value = value.toString()
    return value.charAt(0).toUpperCase() + value.slice(1)
  }
}

usage

{{ layers.name | capitalize }}
trin's avatar

except for the solution from @devingray_ you can use simple computed getter

computed: {
	computedLayers: function () {
		return JSON.parse(JSON.stringify(this.layers)).map(item => {
			item.computedName = 123
			return item
		})
	}
}

and use like computedLayers[0].computedName

1 like

Please or to participate in this conversation.