【问题标题】:Json find in arrayJson 在数组中查找
【发布时间】:2017-08-30 22:20:30
【问题描述】:

我有这个 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 获取产品描述。

【问题讨论】:

  • 你可以使用过滤方法
  • 哦,真的,你的学校老师在家庭作业中给了你这个。

标签: javascript json parsing find


【解决方案1】:
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

【讨论】:

    【解决方案2】:

    使用JSON.parse() 解析json 后,您可以使用find 方法查找具有匹配id 的对象,如果找到对象,您可以得到它的描述。

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-04
        • 2020-04-03
        • 1970-01-01
        • 1970-01-01
        • 2014-05-13
        • 2020-07-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多