Hello guys I hope you are very well, I have the following problem. in the next object
"Customer": {
"Atention": null
}
I need to extract the value of "Atention"
in a function, but this value is dynamic and varies, but it will always have the word 'PORTFOLIO'. For this I am using the following function
function ObtenerValor () {
var data = JSON.parse(body) //Estoy omitiendo la ruta de la respuesta del JSON
var Atention1 = null;
var cadena = data.WSResponseBody.Customer.Atention; //está es la ruta del objeto `Atention` en la respuesta del JSON
var palabra = 'CARTERA';
var index = cadena.indexOf(palabra);
if(index >= 0) {
return Atention1 = "la palabra existe";
} else {
return Atention1 = "la palabra no existe dentro de la cadena";
}
}
ObtenerValor ();
And it works but when the object Atention
has a value other than null, when it comes in null, I get the following error
TypeError: Cannot read properties of null (reading 'indexOf')
I would appreciate any help :)
Looking at the indexOf documentation I see that it could be done like this:
That is, we check if the
cadena
is null on the one hand (because here we define that variable:var cadena = data.Customer.Atention;
and you want to control the possible null value ), or if the text does not correspond to a word through this condition:although you have already said that if it contains something it would be "WALLET", but just in case.
Note: Reading the comments I see that it is the same as what @Mateo told you
You could use a ternary operator, which is basically an if on a single line, and takes 3 arguments, the variable to take into account, what to do when it is true, and what to do when it is not true, in this case if it is not true (word is null), we can return -1, which is what indexOf would return if it didn't have the word