AJAX jquery request generating an array with only one field loaded

Asked

Viewed 41 times

0

i have an array of objects - JSON:

[
{
 "nome": "Luis",
 "numero": 14
},
{
 "nome": "Pedro",
 "numero": 12
},
{
  "nome": "Maria",
  "numero": 1
}
]

how do I make an AJAX (jquery) request that returns only the fields "name":

[{"nome": "Luis"},{"nome": "Pedro"},{"nome": "Maria"}]

or

["Luis","Pedro","Maria"]

i tried with a jquery parameter:

var parametro = {"nome":"Pedro"};    
$.get("[URL]", parametro, [function]);

Of course, it only returned one name element: Pedro. Does anyone know how to return an array (preferably a string array)? thank you.

  • Dude I don’t think that’s possible, when you do the request json comes the way it was formatted by the back end. You’ll have to take care of that at the front, which is pretty simple!

  • As @Leandrade said, either you change the back-end by returning only the names or do as the answer below indicated.

  • ok. is that the return will be "heavy" in the second field. here only has an int, but the idea is to take a monster string and dozens of objects. I thought of something to give me performance.

1 answer

0

I would iterate over the array by taking only the name and adding to a new array of names. As follows:

var names = [];
$.get('http://urlEmquestao', function(response){
   for (var i = 0; i < response.length; i++) {
      names.push(response[i].nome);
   }
});

Browser other questions tagged

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