0
contact1 : {name: "Kesh", relation: "Mother", number: "9819269972"}

this is particular data is part of a bigger json data. I am accessing it via JSONArrayName.contact1. How do i access name, relation and number now?

var obj, dbParam, xmlhttp, myObj, x, txt = "";  
obj = { "table":"Successful", "limit":20 };
dbParam = JSON.stringify(obj); 
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
   if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    myObj = JSON.parse(xmlhttp.responseText);
    console.log(myObj);
    //console.log(myObj[0]);
    document.getElementById("userId").innerHTML = myObj.id;
    document.getElementById("DOB").innerHTML = myObj.dob;
    document.getElementById("bloodGroup").innerHTML = myObj.bloodGroup;
    document.getElementById("aadhar").innerHTML = myObj.aadharCard;
    document.getElementById("allergies").innerHTML = myObj.allergies;
    document.getElementById("insurances").innerHTML = 
    myObj.insuranceDetails;
    var contact1 = myObj.contact1;
    console.log(contact1);

}

console output: myobj:

{id: "123456", insuranceDetails: null, allergies: null, bloodGroup: "A", gender: "Female", contact1: {name: "Kesh", relation: "Mother", number: "9819269972"}, contact2: {name: "Kesh", relation: "Mother", number: "9819269972"}}

contact1:

{name: "Kesh", relation: "Mother", number: "9819269972"}

3
  • what does the console print? Commented Feb 22, 2018 at 14:40
  • Are you sure that xmlhttp.responseText variable is correct JSON? Commented Feb 22, 2018 at 14:45
  • yeah, that is surely correct Commented Feb 22, 2018 at 14:48

4 Answers 4

2

Use Dot-Notation to access the value corresponding to keys in the object.

var JSONArrayName = {contact1 : {name: "Kesh", relation: "Mother", number: "9819269972"}};

console.log(JSONArrayName.contact1.name);
console.log(JSONArrayName.contact1.relation);

Sign up to request clarification or add additional context in comments.

1 Comment

i have editted the above code. Here, if i do myObj.contact1.name i get "undefined" as my console output
0

You can access them by using dot notation like

var data = { contact1 : {name: "Kesh", relation: "Mother", number: "9819269972"} } 
console.log(data.contact1.name);
console.log(data.contact1.relation);
console.log(data.contact1.number);

1 Comment

i have editted the above code. Here, if i do myObj.contact1.name i get "undefined" as my console output
0

can access the data in such a way:

myObj.contact[0].name

Comments

0

In my console it work fine, make sure that you have a non empty variable myObj Console

Comments

Your Answer

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.