1
My problem is this: I am retrieving a Json object from localStorage via Javascript, and I wanted to add a value to one of these attributes, and then save the d evolta object in Storage location. However, when doing the operation: object.attribute = object.attribute + umValueNumeric; what happens is that the values are concatenated into the attribute. That is, instead of 1+1 resulting in two, the result is saved in Json as "11".
In this example below, the current account balance was 122.00 and I tried to add 8772.99.
The two zeroes you have in front is because I couldn’t format the right Pattern yet.
Just follow my code:
function processaConfirmDep(){
var valor = document.getElementById('valorDeposito');
var favorecido = document.getElementById('nomeFav');
var objDep;
var cliente = localStorage.getItem(favorecido.value);
var clienteConta = JSON.parse(cliente);
var agenciaFav = clienteConta.agencia;
var contaFav = clienteConta.conta;
objDep = {
id : "12",
agenciaFav : agenciaFav.value,
contaFav : contaFav.value,
valor : valor.value
}
clienteConta.saldo = clienteConta.saldo+valor.value;
var clienteDeposito = createMyObject("DepositoLucas", [clienteConta, objDep]);
localStorage["DepositoLucas"] = JSON.stringify(clienteDeposito);
localStorage[clienteConta.nome] = JSON.stringify(clienteConta);
}
Result on Storage Location. (See the "Lucas" key object, attribute "Balance"):
{"DepositoLucas":[{"nome":"Lucas","agencia":"33333","conta":"4123","saldo":"0122,008772,99"},{"id":"12","valor":"8772,99"}]}
Lucas {"nome":"Lucas","agencia":"33333","conta":"4123","saldo":"0122,008772,99"}
Before doing the operation. You must convert the data to the type number. You can use the function
parseFloat()
. Because in this way what is happening is an operation on strings. So a concatenation is made.– GeekSilva
Ah, when converting the data. Remember to replace the comma (,) with a dot (.). That is: 122.00 would be 122.00
– GeekSilva