Add json object property

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>
The increase part works normal ..     
asked by anonymous 02.08.2018 / 12:35

2 answers

2

Your code has two small errors. See:

var mult = data.qtd++;

The way it is, as you're using post-increment operator, you're basically doing this:

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

With this the value of mult becomes 0 and when doing the multiplication, logically it will return 0 also.

If you do not want to change the value of data.qtd , look like this:

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;

In this way you alteate the value of the variable and then with the updated value you assign it.

And in the last code snippet of the add()

mult * data.vlr_produto

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

OBS: In this reply , I explain a bit how the operator of powders and prewash.

    
02.08.2018 / 12:54
1

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

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>
    
02.08.2018 / 14:01