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);
});
programtreasures
4,2882 gold badges14 silver badges30 bronze badges
asked Dec 14, 2017 at 7:58
inaz
1,8035 gold badges24 silver badges44 bronze badges
3 Answers 3
Try with the following code:
var re = research.rooms[0].adultcount
jeprubio
18.1k5 gold badges51 silver badges62 bronze badges
answered Dec 14, 2017 at 8:00
Kiran Shinde
6,0326 gold badges30 silver badges45 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
});
answered Dec 14, 2017 at 8:01
programtreasures
4,2882 gold badges14 silver badges30 bronze badges
4 Comments
sujit tiwari
Error: { "message": "Uncaught ReferenceError: $ is not defined", "filename": "stacksnippets.net/js", "lineno": 13, "colno": 9 }
programtreasures
jquery is missing, please check jsbin demo
sujit tiwari
That's what I wanted to say to add jquery to snippet
programtreasures
sorry actually I dont know how to add jquery in snippet. can you edit if you know? thanks
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);
}
Comments
lang-js
research.roomsis array.adultcountis object inside array. Access it with index