Mount array through a list in ajax

Asked

Viewed 1,271 times

2

I have an ajax function that consumes a webservice ,and returns me a list, as I take this list and mount two arrays with the values?

JS:

function getCars() {
$.ajax({
  type: "POST",
  url: "CarService.asmx/GetAllCars",
  data: "MethodName=GetAllCars",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(response) {

    //QUERO MONTAR OS ARRAYS AQUI 
    });
  },
  failure: function(msg) {
    $('#output').text(msg);
  }
});

}

I want to take the return of this list and put together two arrays. Ex: the list returns 5 records, with ID, value, and car color. I want to mount two arrays, one for color and one for Ex value:

var cor = [];
var valor = [];

I want to fill in the 3 records returned in the list, IE, 3 colors and 3 value, getting

cor['red','blue','blue'] 
valor ['20.5','30.5','50.5']

Only that.

2 answers

3


Supposing the return of your webservice is something like:

response = [ 
 {"Id": 1, "Valor": "10.000", "Cor": "Azul"}, 
 {"Id": 2, "Valor": "15.000", "Cor": "Verde"}, 
 {"Id": 3, "Valor": "12.000", "Cor": "Vermelho"}
];    

Use the method push to popular the array:

$.each(response, function(i, item) {
    cor.push(item.Cor);
    valor.push(item.Valor);
});
  • that i, is the Indice? another question, can I declare the arrays outside the function to be ultimalized in any other?

  • That’s right. Yes, take a look in that reply! @Warlock

  • Thanks lucius, this answers my other topic that I think was misunderstood, see http://answall.com/questions/80970/grafico-highcharts-com-webservice answers there, because there would be in practice, obg :)

2

as an alternative to the Lucio method, you can also use the native Javascript map, where it mounts an array using the function return.

Also note that you can continue to manipulate the array using native methods such as Sort (to sort) and filter (to filter).

In the example below I use the map to kill the two arrays, right after the Sort and filter to sort colors alphabetically and remove duplicates.

response = [ 
  {ID: 1, Valor: 20.5, Cor: "red"}, 
  {ID: 2, Valor: 30.5, Cor: "blue"}, 
  {ID: 3, Valor: 50.5, Cor: "blue"}
]; 

var valor = response.map(function (item) { return item.Valor; });
var cor = response.map(function (item) { return item.Cor; });
var filtro = cor.sort().filter(function (item, indice) { return cor.indexOf(item) == indice; });

console.log(filtro);

  • Very good! : ) @Tobymosque

Browser other questions tagged

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