0

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
2
  • Here research.rooms is array. adultcount is object inside array. Access it with index Commented Dec 14, 2017 at 8:00
  • research.rooms[0].adultcount Commented Dec 14, 2017 at 8:08

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

answered Dec 14, 2017 at 8:01

4 Comments

Error: { "message": "Uncaught ReferenceError: $ is not defined", "filename": "stacksnippets.net/js", "lineno": 13, "colno": 9 }
jquery is missing, please check jsbin demo
That's what I wanted to say to add jquery to snippet
sorry actually I dont know how to add jquery in snippet. can you edit if you know? thanks
0

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);
}
marc_s
760k186 gold badges1.4k silver badges1.5k bronze badges
answered Dec 14, 2017 at 8:03

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.