Replace value undefined javascript

-1

Within my dashboard, the user makes a filter that goes to the database and returns a JavaScript object through an asynchronous request and the array extension can vary, being able to have a length from 1 to 3, always !

So sometimes when the user does the filter, on my console it returns the following:

Andwhenyouclickonthelog,inthisexample,thekey2ofthearrayismarked,indicatingthatitisundefined.Icheckedthedatabaseandeverythingandthat'sit.

SoforthisIlookedintheforumonthesubjectandIbuiltthisfunctionthatisbeingusedasintheimageabove:

functiontratarValorIndefinido(vl){if(typeof(vl)==="undefined"){
        vl ="S/ HISTÓRICO";
    }
};

But instead of stamping "S / HISTORY", it is returning undefined .

Where am I going wrong?

*** HOW DO I CURRENT OBJECT?

var dataBar = {
    labels: [dataChart[0]['mesReferencia'],dataChart[1]['mesReferencia'],dataChart[2]['mesReferencia']], 
    datasets: [{
        label: "CPF's Enviados", 
        backgroundColor: "rgba(0,51,90,0.8)",
        borderColor: "rgba(0,51,90,0.9)",
        borderWidth: 2,
        hoverBackgroundColor: "rgba(0,51,90,0.9)",
        hoverBorderColor: "rgba(0,51,90,1)",
        data: [dataChart[0]['cpfsEnviados'],dataChart[1]['cpfsEnviados'],dataChart[2]['cpfsEnviados']]
    },

** structure of data[0] :

    
asked by anonymous 03.01.2017 / 21:52

2 answers

2

Any Javascript function that does not declare a return with the keyword return , returns undefined by default.

I think that's all that is missing. return vl; at the end of the function should solve your problem. Or, return "S/ HISTÓRICO" direct.

    
03.01.2017 / 21:54
1

I would suggest for you to go through the list itself and find% cos_de% change the direct value in the object. An example of the list might be:

[
 {id: 1, mesReferencia: "Jan"},
 {id: 2, mesReferencia: undefined}
];

And use the Array # forEach to modify the value:

arrayDeObjetos.forEach(function(item) {
  if (typeof item.mesReferencia === "undefined") item.mesReferencia = "S/ HISTÓRICO";
});

Example:

var itens = [
 {id: 1, mesReferencia: "Jan"},
 {id: 2, mesReferencia: undefined}
];

itens.forEach(function(item) {
  if (typeof item.mesReferencia === "undefined") item.mesReferencia = "S/ HISTÓRICO";
});
  
console.log(itens);
    
03.01.2017 / 22:04