【问题标题】:How can I get data in json array by ID如何通过 ID 获取 json 数组中的数据
【发布时间】:2011-12-31 02:54:49
【问题描述】:

我有问题,请你帮帮我! 我有一个 json 数组:

"category" : [
{
    id: 1,
    product: [{id : product_1, type : ball}] 
},
{
    id : 2,
    product :[{id : product_2, type : pen}]
}
]

我的问题是:如果我有一个链接,例如:http://test/category/1 那么,我该如何按 id = 1 的类别获取产品信息? 感谢您的任何建议:)

【问题讨论】:

    标签: javascript jquery html ajax json


    【解决方案1】:

    这是一种无需使用 for 即可在一行中完成的方法:

    function filterById(jsonObject, id) {return jsonObject.filter(function(jsonObject) {return (jsonObject['id'] == id);})[0];}
    

    然后如果你想获取,例如,id=2 的对象,你只需使用:

    var selectedObject = filterById(yourJson['category'], 2);
    

    然后 selectedObject 将根据您的示例获取此值:

    {
        id : 2,
        product :[{id : product_2, type : pen}]
    }
    

    有一个缺点:旧浏览器,例如 IE8,不支持 filter() 所以你需要添加这个 polyfill 代码来兼容旧浏览器: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Polyfill

    【讨论】:

      【解决方案2】:

      假设您的数据结构如下所示:

      var data = {
          "category" : [
          {
              id: 1,
              product: [{id : product_1, type : ball}] 
          },
          {
              id : 2,
              product :[{id : product_2, type : pen}]
          }
          ]
      }
      

      然后,您可以像这样在数组中搜索 id == 1 的类别数组中的项目:

      function findId(data, idToLookFor) {
          var categoryArray = data.category;
          for (var i = 0; i < categoryArray.length; i++) {
              if (categoryArray[i].id == idToLookFor) {
                  return(categoryArray[i].product);
              }
          }
      }
      
      var item = findId(data, 1);
      // item.id, item.type
      

      【讨论】:

      • 它老了。但为什么不标记为答案?工作完美。
      【解决方案3】:

      如果您将类别数组保存在 categories JS 变量中,您可以像这样基于简单的 JavaScript(没有 jQuery)过滤这个数组:

      var result = categories.filter(function(element){
          if (element.id == 2){
              return true;
          } else {
              return false;
          }
      });
      

      然后在result[0].product 中,您将拥有特定类别中的一系列产品。

      请参阅this jsfiddle 以获得证明。

      附言。 filter() 方法并非在所有浏览器中都可用,您可能需要应用一些代码,以便在需要但未找到时使其可用。以下是 Mozilla Developers Network 上有关 filter() 的详细信息以及使其在旧浏览器上运行所需的代码的一些文章:MDN: filter()

      【讨论】:

        【解决方案4】:

        我认为 OP 想要从 url 检索相应的数据

        所以第一步是将url映射到标识符

        var urlParts = window.location.href.split(/\//)
        //window.location.href = http://domain.com/category/1
        // urlParts = ['http:', '', 'domain.com', 'category', '1']
        var id = urlParts.pop();
        var category = urlParts.pop();
        

        然后你用JSON.parse从JSON字符串中检索数据:

        var data = JSON.parse('{"category" : [{"id": 1, "product": [{"id" : "product_1", "type" : "ball"}] }, {"id" : 2, "product" :[{"id" : "product_2", "type" : "pen"}] } ]}');
        
        //The data structure
        // {"category" : [
        //   {"id": 1, "product" : 
        //     [
        //       {"id" : "product_1", "type" : "ball"}
        //     ]},
        
        //   {"id" : 2, "product" :
        //     [
        //       {"id" : "product_2", "type" : "pen"}
        //     ]} 
        // ]}
        

        最后,你可以用idcategory检索类似@jfriend00的帖子的数据

        function findId(data, idToLookFor) {
            var categoryArray = data.category;
            for (var i = 0; i < categoryArray.length; i++) {
                if (categoryArray[i].id == idToLookFor) {
                    return(categoryArray[i].product);
                }
            }
        }
        
        var item = findId(data.category, id);
        // item.id, item.type
        

        【讨论】:

          【解决方案5】:

          您可能已经找到了答案,但如果还没有,您可以简单地使用逻辑 OR (||) 运算符。

          在您的情况下,您可以使用 jQuery 的 ajax() 方法。要根据ids 获取您的产品,只需使用以下简单逻辑:

          var prodID1 = 1, prodID2 = 2;
          if(this.id == prodID || this.id == prodID2) {
            //write your JSON data, etc.
            //push to array, etc.
          }
          

          【讨论】:

            猜你喜欢
            • 2021-05-04
            • 2013-01-22
            • 1970-01-01
            • 1970-01-01
            • 2019-03-19
            • 2020-10-26
            • 2017-01-07
            • 1970-01-01
            • 2021-02-15
            相关资源
            最近更新 更多