2017-04-05 10 views
-3

で見つける私はこのJSONを持っている:JSON配列

{ 
"response":{ 
    "name":"Demo Shop", 
    "items":[ 
     { 
      "id":3, 
      "name":"first", 
      "cost":10, 
      "description":"First description" 
     }, 
     { 
      "id":2, 
      "name":"second", 
      "cost":50, 
      "description":"second description" 
     } 
    ], 
    "coupon":false 
} 
} 

私はこのJSONを解析し、IDによって、製品の説明を取得する必要があります。

+0

あなたは本当にフィルタ法 – user93

+0

おおを使用することができますし、あなたの学校の先生は宿題で、あなたにこれを与えました。 – Panther

答えて

1

あなたはJSON.parse()でJSONをパースした後、あなたが一致するidを持つオブジェクトを見つけるために、findメソッドを使用することができますし、オブジェクトが見つかった場合は、その取得することができます説明。

var json = '{"response":{"name":"Demo Shop","items":[{"id":3,"name":"first","cost":10,"description":"First description"},{"id":2,"name":"second","cost":50,"description":"second description"}],"coupon":false}}' 
 

 
var desc = JSON.parse(json).response.items.find(function(e) { 
 
    return e.id == 3 
 
}) 
 

 
if(desc) { 
 
    console.log(desc.description) 
 
}

0

filterを使用して、このような何かを試してみてください:

var json = { 
 
    "response":{ 
 
     "name":"Demo Shop", 
 
     "items":[ 
 
      { 
 
       "id":3, 
 
       "name":"first", 
 
       "cost":10, 
 
       "description":"First description" 
 
      }, 
 
      { 
 
       "id":2, 
 
       "name":"second", 
 
       "cost":50, 
 
       "description":"second description" 
 
      } 
 
     ], 
 
     "coupon":false 
 
    } 
 
} 
 

 
var result = json.response.items.filter(function(item) { 
 
    return item.id === 3; //Change 3 to what you want to search for 
 
}); 
 

 
if(result.length > 0) { 
 
    console.log(result[0].description); 
 
}

0
var json=[{"name":"Lenovo Thinkpad 41A4298","website":"google"}, 
{"name":"Lenovo Thinkpad 41A2222","website":"google"}, 
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"}, 
{"name":"Lenovo Thinkpad 41A424448","website":"google"}, 
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"}, 
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"}, 
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"}, 
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]; 


var as=$(json).filter(function (i,n){return n.website==='yahoo'}); 



for (var i=0;i<as.length;i++) 
    { 
    alert(as[i].name +"   "+as[i].website) 
} 

http://jsbin.com/yakubixi/4/edit?html,css,js,output