-3
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var myObj = JSON.parse(this.responseText);
    document.getElementById("demo").innerHTML = myObj.name;
  }
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();



{
"name":"John",
"age":31,
"pets":[
    { "animal":"dog", "name":"Fido" },
    { "animal":"cat", "name":"Felix" },
    { "animal":"hamster", "name":"Lightning" }
]}

how do i reference the values in the pets array. as shown above i can reference the the name value but when ever i try to reference the values of animal inside pets. it returns just [object Object]

Jai
  • 74,255
  • 12
  • 74
  • 103
codebeast
  • 41
  • 1
  • 6

5 Answers5

2

You need to loop the "pets".Like

  var dataArry = {
           "name":"John",
           "age":31,
           "pets":[
             { "animal":"dog", "name":"Fido" },
             { "animal":"cat", "name":"Felix" },
             { "animal":"hamster", "name":"Lightning" }
        ]}


   dataArry.pets.forEach(function(eachPet) {
        console.log(eachPet);
    });

You need to use foreach function.Hope this will help you.

ArunJaganathan
  • 695
  • 2
  • 7
  • 20
1

Try this:

myObj.pets.map(function(item){ console.log(item) })

this will give you the following result:

{animal: "dog", name: "Fido"}

{animal: "cat", name: "Felix"}

{animal: "hamster", name: "Lightning"}

to access single animal's name use

myObj.pets.map(function(item){ console.log(item.name); })

to get animal use:

myObj.pets.map(function(item){ console.log(item.animal); })

Another option is to use:

for(var pet of myObj.pets)
{
  console.log(pet.animal); //for animal
  console.log(pet.name); //for name
}
Devinder
  • 127
  • 1
  • 10
1

try

myObj.pets.forEach(function (pet) {
    console.log(pet); // What you need is probably *pet.name*
});
holydragon
  • 6,158
  • 6
  • 39
  • 62
1

Try this.

    var pets= myObj.pets;
    for(var i=0;i<pets.length;i++){
        console.log(pets[i].name);
    }
Atal Prateek
  • 541
  • 3
  • 7
-1

You can access like this *edit: with jQuery.each() *

        var person = {
        "name":"John",
        "age":31,
        "pets":[
            { "animal":"dog", "name":"Fido" },
            { "animal":"cat", "name":"Felix" },
            { "animal":"hamster", "name":"Lightning" }
        ]};

        $.each(person.pets,function (k,v) {
            console.log(v.animal, v.name);
        });
  • Ehh ... jQuery is not tagged nor included in OP's code, why to answer with jQuery then? The task at hands seems to be pretty trivial, an enormous library is not needed to solve the problem. – Teemu Dec 14 '18 at 12:05