2
I have a function that I will adapt to a button, which will exchange a data within an array, between S
and N
.
The code I have is:
var array = [{"nome":"1","faltou":"N","goleiro":"N","pago":"N"},{"nome":"2","faltou":"N","goleiro":"N","pago":"N"},{"nome":"3","faltou":"N","goleiro":"N","pago":"N"}];
function toggleArrayItem(a, v, d) {
var i = a.findIndex(function(val){
return val.nome === v;
});
if (i != -1){
var data = a[i];
if(d === 'faltou'){
const isOn = (data.faltou = 'N');
a[i] = ({"nome":data.nome, "faltou":isOn ? 'N' : 'S', "goleiro":data.goleiro, "pagou":data.pagou});
} else if(d === 'goleiro'){
const isOn = data.goleiro = 'N';
a[i] = ({"nome":data.nome, "faltou":data.faltou, "goleiro":isOn ? 'N' : 'S', "pagou": data.pagou});
} else if(d === 'pagou'){
const isOn = data.pagou = 'N';
a[i] = ({"nome":data.nome, "faltou":data.faltou, "goleiro":data.goleiro, "pagou": isOn ? 'N' : 'S'});
}
}
}
toggleArrayItem(array, '1', 'faltou');.
Only it is not working properly, and wanted to decrease the code. I am using localStorage in JSON.
How to proceed?
Thank you for the @Isac reply. I’m almost sure that this Arrow Function does not work properly in hybrid apps on Android 4.4 and 5, but I will test and already give an opinion.
– Guilherme Lirio
@Guilhermelirio No problem. If it doesn’t work just put the
findIndex
as it had originally. But I already say that it is unlikely that supportfindIndex
and not Arrow Functions. If you look at the caniuse with. and even on MDN sees that the support is very high leaving out only the classic IE.– Isac
I will test. In HTML it worked perfectly. Thanks for the help!
– Guilherme Lirio
i am the type of person who likes to understand the code: could explain to me what does . includes(d) in your code?
– Guilherme Lirio
@Guilhermelirio Understanding the whole code is always ideal. o
includes
is a array method that tests whether the array contains an element. It is a way to avoid having to doif (d === 'faltou' || d == 'goleiro' || d === 'pagou')
, which usually gets longer but in your case it didn’t get as long because the variabled
has a very short name.– Isac