如何在json文件中访问数组中的数组

hwazgwia  于 2023-03-24  发布在  其他
关注(0)|答案(6)|浏览(154)
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" }
]}

我如何引用pets数组中的值。如上所示,我可以引用name值,但当我试图引用pets中的animal值时。它只返回[object Object]

qjp7pelc

qjp7pelc1#

你需要循环“宠物”。比如

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);
    });

你需要使用foreach函数。希望这对你有帮助。

wixjitnu

wixjitnu2#

尝试

myObj.pets.forEach(function (pet) {
    console.log(pet); // What you need is probably *pet.name*
});
xcitsw88

xcitsw883#

试试这个。

var pets= myObj.pets;
    for(var i=0;i<pets.length;i++){
        console.log(pets[i].name);
    }
xoefb8l8

xoefb8l84#

试试这个:

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

这将给予以下结果:
{animal:“dog”,name:“Fido”}
{animal:“cat”,name:“Felix”}
{animal:“hamster”,name: lightning
访问单个动物的名称使用

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

to get animal动物用途:

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

另一个选择是用途:

for(var pet of myObj.pets)
{
  console.log(pet.animal); //for animal
  console.log(pet.name); //for name
}
bhmjp9jg

bhmjp9jg5#

你可以这样访问 *edit: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);
        });
cbjzeqam

cbjzeqam6#

手鼓

const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  let pets = myObj.pets;
  for(let i = 0; i < pets.length; i++){
        document.getElementById("demo").innerHTML += pets[i].name+ "</br>";
  }
  
  
 
}
xmlhttp.open("GET", "json_demo.txt");
xmlhttp.send();

相关问题