inaz
inaz

Reputation: 1775

How to separate Json fields and put them in variables

I have a JSON and I Want to separate each field of that and then I want to use of each field separately .

I wrote below code but it does not work correctly and return undefined in alert.

here is my code :

$( document ).ready(function() {
var research=
{
  "city":"1186432",
   "hotelname":"OKHTINSKAYA",
   "indate":"2017-12-23",
   "outedate":"2017-12-30",
   "rooms":[
      {
         "adultcount":"1",
         "childcount":"1,1"
      },
      {
         "adultcount":"1",
         "childcountandage":"0 "
      }
   ]
}
var re = research.rooms.adultcount
alert(re);
});

Upvotes: 0

Views: 238

Answers (3)

Elad
Elad

Reputation: 2377

research.rooms is an array, so to get access for each room in this array- you have to loop throw it.

For example:

research.rooms.map( room => alert(room.adultcount));

Or, in older js syntax:

for(var i = 0; i < research.rooms.length; i++){
    alert(research.rooms[i].adultcount);
}

Upvotes: 0

programtreasures
programtreasures

Reputation: 4298

use index to consume array property research.rooms[0].adultcount,

$( document ).ready(function() {
var research=  {
  "city":"1186432",
   "hotelname":"OKHTINSKAYA",
   "indate":"2017-12-23",
   "outedate":"2017-12-30",
   "rooms":[
      {
         "adultcount":"1",
         "childcount":"1,1"
      },
      {
         "adultcount":"1",
         "childcountandage":"0 "
      }
   ]
}
var re = research.rooms[0].adultcount
alert(re);
});

demo https://jsbin.com/zefojozevo/edit?js,console,output

Upvotes: 1

Kiran Shinde
Kiran Shinde

Reputation: 5982

Try with the following code:

var re = research.rooms[0].adultcount

Upvotes: 2

Related Questions