-2

There is data in the request at the name of url '/r/rr-autocomplete/?q=string':

{"results": [{"id": "371", "text": "strstr", "selected_text": "strstr"}], "pagination": {"more": false}}

I want with jQuery to query the data and write the value of the id to the variable. My js code

    $.get('r/rr-autocomplete/?q=string', function (data) {
    console.log(data.results)
})

In the console, I get the desired array, but I do not know how to write the id value.

{
"id": "371",
"text": "strstr",
"selected_text": "strstr"
}

I will be glad for any help.

Echo Foe
  • 398
  • 1
  • 2
  • 16
  • 1
    The question is unclear but most likely one (or both) of these links has the answer: [Working with objects - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) and/or [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Andreas Jul 29 '22 at 16:00
  • Have you tried **console.log(data.results.id)**? – imvain2 Jul 29 '22 at 16:01
  • @imvain2 `data.results` is an array... – Andreas Jul 29 '22 at 16:01
  • @Andreas, that's what I was seeing too but then the console was outputting an object which was my confusion. But you are correct, so its just console.log(data.results[0].id) – imvain2 Jul 29 '22 at 16:10

1 Answers1

-1

To write to a variable id, need the following:

let value = data.results[0].id
E_net4
  • 27,810
  • 13
  • 101
  • 139
Echo Foe
  • 398
  • 1
  • 2
  • 16