Error while receiving variable JSON

Asked

Viewed 73 times

0

That way I can get my values back:

   var unidades: "101|102|103|104";

    function getValue(key, array) {
      for (var el in array) {
        if (array[el].hasOwnProperty(key)) {   
            return array[el][key];
        }
      }
    }

    var jsonTitles = [{"101":"20","102":"2","103":"98","104":10}];                  
    var quebra = unidades.split("|");

    for (var i = quebra.length - 1; i >= 0; i--) {
        var unidade = quebra[i];
        $("#lista").append("<p>" +getValue(unidade, jsonTitles)+"</p>");
    }

That way I NAY I can recover the values:

    var unidades: "101|102|103|104";

    function getValue(key, array) {
      for (var el in array) {
        if (array[el].hasOwnProperty(key)) {   
            return array[el][key];
        }
      }
    }

    var jsonTitles = latGas;                    
    var quebra = unidades.split("|");

    for (var i = quebra.length - 1; i >= 0; i--) {
        var unidade = quebra[i];
        $("#lista").append("<p>" +getValue(unidade, jsonTitles)+"</p>");
    }

The variable latGas comes from an AJAX query

  • Ever tried to use parseJSON on your object? It may be that it is being interpreted as string. Try this: var jsonTitles = jQuery.parseJSON(latGas)

  • thanks @Ricardopunctual on the fly! Something else... where I repeat that string would have to sort the values in descending or ascending order?

1 answer

1


By answering your question, by parsing you can have an array of objects:

var jsonTitles = jQuery.parseJSON(latGas);

To sort, just use the method sort of the object array:

// Ordem crescente
jsonTitles.sort(function(a, b){return b-a});
// Ou ordem decrescente:
jsonTitles.sort(function(a, b){return a-b});

Reference: https://www.w3schools.com/jsref/jsref_sort.asp

Browser other questions tagged

You are not signed in. Login or sign up in order to post.