Sum json object property

Asked

Viewed 295 times

0

I have a json object and need to multiply the value vlr_produto with the function add()

data={
  id: 6,
  nome_produto: "Produto",
  vlr_produto: 16.98,
  qtd: 0
}
add(data) {
  var mult = data.qtd++;
  mult * data.vlr_produto;
}
<span (click)="add(data)">+</span>
<div>{{vlr_produto}}</div>
Increment part works normal..

2 answers

2


Your code has two small errors. See:

var mult = data.qtd++;

The way it is, how you’re using post increment operator, you’re basically doing this:

var mult = data.qtd;
data.qtd++;

Hence the value of mult stays 0 and when doing the multiplication, logically will return 0 also.

If you do not want to change the value of data.qtd try to do so:

var mult = data.qtd + 1;

But if you really need to change the value of data.qtd, you can do so:

var mult = ++data.qtd;

This way you change the value of the variable and then with the updated value you assign it.

And in the last code snippet of the function add()

mult * data.vlr_produto

You are multiplying right, but you are doing nothing but multiply, the result of multiplication is being "lost". Since you’re not doing anything with it, you’re not assigning in a variable, you’re not returning, you’re not printing.

OBS: In that reply, i explain a little how the post operator works and pre trouble.

1

In the example below the add function increments the quantity and then multiplies by the value of the product. Done, arrow the value to the total property of the object.

data = {
  id: 6,
  nome_produto: "Produto",
  vlr_produto: 16.98,
  qtd: 0,
  total: 0
};

add(data) {
   data.total = data.vlr_produto * (++data.qtd)
}
<span (click)="add(data)">+</span>
<div>{{total}}</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.