-1

我知道这对你们中的一些人来说可能看起来很基础,但我正在尝试用 jquery 迭代一个 json 对象,如何访问每个生产者的每个网页名称。请帮忙!底部是我的代码,欢迎提供任何帮助。

{
    "producers": [
        {
            "producer": {
                "id": "1",
                "name": "Radosa",
                "address": " Grenvägen 1-3",
                "zipcode": " 577 39",
                "district": " Hultsfred",
                "webpage": [
                    {
                        "name": "waste",
                        "purpose": "sample "
                    },
                    {
                        "name": "Ultra Worker",
                        "purpose": "Posao"
                    }
                ],
                "logoURL": "../producenter/images/ema.png",
                "latitude": "57.4999",
                "longitude": "15.828"
            }
        },
        {
            "producer": {
                "id": "2",
                "name": "Marko",
                "address": " Grenvägen 1-3",
                "zipcode": " 577 39",
                "district": " Hultsfred",
                "webpage": [
                    {
                        "name": "Sample name",
                        "purpose": "sample purpose"
                    },
                    {
                        "name": "Sample name",
                        "purpose": "sample purpose"
                    }
                ],
                "logoURL": "../producenter/images/ema.png",
                "latitude": "57.4999",
                "longitude": "15.828"
            }
        }
    ]
}


$.each(data.producers, function(key, value) {
        console.log(value.producer); ------ this works,
        console.log(value.webpage.name); ------ this don't work. How to reach this value?
    });
4

4 回答 4

2
console.log(value.webpage.name);

应该

// webpage is an array too, get the first element of it for example
console.log(value.producer.webpage[0].name);
于 2013-09-24T10:53:30.880 回答
1

说你的 json 对象是数据

尝试这个

 $.each(data.producers,function(i,v){
     $.each(v.producer.webpage,function(i1,v1){ //<--since webpage is an array, use each again...
         alert(v1.name);
     })
 });

或者干脆你可以使用 index..

 $.each(data.producers,function(index,value){
    console.log(value.producer.webpage[0].name); //first name
     console.log(value.producer.webpage[0].name); //second name
 });
于 2013-09-24T10:55:10.027 回答
0

Sou 可以这样做:

for(var producer in Object.producers){
    if(Object.producers.hasOwnProperty(producer)  && Object.producers[producer].webpage!==undefined){
        for(var i=0; i<Object.producers[producer].webpage.length; i+=1){
          // Your further code here
        }
    }
}
于 2013-09-24T10:56:55.090 回答
0

因为value.producer.webpagearray你需要:

for(var i=0; i<value.producer.webpage.length; i++) {
   var webpage = value.producer.webpage[i];
   console.log(webpage.name);
}
于 2013-09-24T10:56:13.840 回答