1👍
maybe you need a getter function for amount:
a = ({
quantity: '',
price: '',
get amount() {
return +this.quantity + +this.price;
}
})
then you may access a.amount
for the sum of quantity and price.
1👍
Though I think the operation should be ‘multiplication’ instead of ‘additon’.
Try the following:
var array = [{ quantity: 10, price: 200, amount: '' },{ quantity: 5, price: 100, amount: '' }]
var newArray = array.map(function(elem, index){
array[index].amount = array[index].quantity + array[index].price
return;
});
console.log(array);
0👍
Since you are using vuejs
you can easily achieve your objective by using [computed][1]
properties.
Example:
export default {
data () {
return {
quantity: '',
price: ''
}
},
computed: {
amount () {
return this.quantity + this.price
}
}
}
Note that computed
properties can’t be set like this.computedProp = someValue
and they are not functions
, they can be used just like data
properties.
0👍
You could create a new component that related to the item in the list
var vm = new Vue({
el: '#example',
data: {
quantity: '',
price: ''
},
computed: {
amount: function(){
return this.quantity * this.price
}
}
})
And then create a computed property based on the quantity and price.
0👍
There are a couple of plain javascript options. I did not mention any Vue-specific stuff.
The easiest one, to me, would be to add a getAmount
-method to your objects, which would return the amount based on your other two properties.
e.g.
var item = {
quantity: 3,
price: 5.00,
getAmount: function () {
return this.quantity * this.price
}
}
Although I’d with null
as default values.
A second option is to use object descriptors. You can create an object using Object.create()
or add properties to an already existing object using Object.defineProperty()
. Both of these methods allow you to pass an object descriptor, where you can define a getter
for your property, which will calculate your desired value based on your other fields.
e.g.
var item = Object.create({
quantity: null,
price: null,
}, {
amount: {
get: function () { return this.quantity*this.price }
}
})
Now, the amount
property will return quantity * price
, just by doing item.amount
.
0👍
To calculate the price based on quantity simply use {{ item.price * item.quantity }}
. I assume you don’t want to clutter your database with an unneeded total field 🙂
Example (including total price)
new Vue({
el:'#app',
data: {
list: [
{ name: 'foo', quantity: 2, price: 20 },
{ name: 'bar', quantity: 3, price: 150 },
{ name: 'baz', quantity: 1, price: 80 }
]
},
computed: {
total(){ return this.list.reduce( (total, item) => item.price * item.quantity + total ,0);},
}
})
ul {list-style:none;}
li:last-child { border-top:1px solid;border-bottom:3px double;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<div id="app">
<ul>
<li v-for="item in list">
{{ item.name}}: {{ item.price * item.quantity}}
</li>
<li>Total: {{ total }}</li>
</ul>
</div>