Mount array through a list in ajax

2

I have an ajax function that consumes a webservice, and returns me a list, how do I get that list and I 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 get the return of this list and mount two arrays. Ex: the list returns 5 records, with ID, value, and car color. I want to mount two arrays, one for color and another for the value Ex:

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

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

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

That's all.

    
asked by anonymous 16.08.2015 / 18:11

2 answers

3

Assuming 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 push method to populate the array:

$.each(response, function(i, item) {
    cor.push(item.Cor);
    valor.push(item.Valor);
});
    
16.08.2015 / 19:09
2

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

Note also that you can continue to manipulate the array using native methods, such as sort and filter.

In the example below I use the map to kill the two arrays, right after the sort and the filter to sort the colors alphabetically and remove the 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);
    
16.08.2015 / 19:44