admin管理员组文章数量:1415460
I have this 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
}
}
I need to parse this json and get description of product by id.
I have this 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
}
}
I need to parse this json and get description of product by id.
Share Improve this question asked Apr 5, 2017 at 10:43 LowderLowder 351 gold badge1 silver badge7 bronze badges 2- you could use filter method – user93 Commented Apr 5, 2017 at 10:43
- 1 Ohh really and your school teacher gave you this in homework. – Panther Commented Apr 5, 2017 at 10:45
3 Answers
Reset to default 2After you parse json with JSON.parse()
you can use find method to find object with matching id and if object is found you can get its description.
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)
}
Try something like this using 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);
}
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./yakubixi/4/edit?html,css,js,output
本文标签: javascriptJson find in arrayStack Overflow
版权声明:本文标题:javascript - Json find in array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745185268a2646653.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论