Home > database >  How can I write a key value to a variable?
How can I write a key value to a variable?

Time:07-30

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.

CodePudding user response:

Maybe like this:

var data = {"results": [{"id": "371", "text": "strstr", "selected_text": "strstr"}], "pagination": {"more": false}}; /* this your return data */
 
 console.log(data.results); /* this is array !!! */
 /* foreach array */
 for(var key in data.results){
    var id = data.results[key]['id']; /* this your variable */
    console.log('id -> '   id);
 }

CodePudding user response:

To write to a variable id, need the following:

let value = data.results[0].id
  • Related