JSON过滤器方法在IE上产生语法错误,但在其他浏览器上可以正常工作

时间:2018-10-14 17:03:10

标签: jquery json

嗨,我有一个嵌套的JSON,我想为空数量值过滤数据

这是原始的JSON-

var unfilteredJSON = {  
   "payload":{  
      "oldKeys":[  
         "125262"
      ],
      "keyData":[  
         {  
            "key":"123456",
            "products":[  
               {  
                  "prodId":"H1",
                  "qty":"1"
               },
               {  
                  "prodId":"H2",
                  "qty":""
               }
            ],
            "rushFee":"true"
         },
         {  
            "key":"234234",
            "products":[  
               {  
                  "prodId":"H1",
                  "qty":"1"
               },
               {  
                  "prodId":"H2",
                  "qty":""
               }
            ],
            "rushFee":"false"
         }
      ],
      "submit":"false"
   }
}

qty键的对象中可以有空值。我想使用jQuery方法过滤数据并删除具有空白数量的对象,以便JSON可以像这样-

 {  
  "payload":{  
     "oldKeys":[  
        "125262"
     ],
     "keyData":[  
        {  
           "key":"123456",
           "products":[  
              {  
                 "prodId":"H1",
                 "qty":"1"
              },
           ],
           "rushFee":"true"
        },
        {  
           "key":"234234",
           "products":[  
              {  
                 "prodId":"H1",
                 "qty":"1"
              },
           ],
           "rushFee":"false"
        }
     ],
     "submit":"false"
  }
 }

所以,我使用了filter方法,可以得到上述结果,效果很好-

   var unfilteredJSON = {"payload":{"oldKeys":["125262"],"keyData": 
  [{"key":"123456","products":[{"prodId":"H1","qty":"1"}, 
  {"prodId":"H2","qty":""}],"rushFee":"true"},{"key":"234234","products": 
  [{"prodId":"H1","qty":"1"}, 
  {"prodId":"H2","qty":""}],"rushFee":"false"}],"submit":"false"}};
   unfilteredJSON.payload.keyData.forEach(e => 
     e.products = e.products.filter(p => p.qty)
  );
   console.log(unfilteredJSON);

但是由于这一行,它给了我Internet Explorer中的语法错误-

 unfilteredJSON.payload.keyData.forEach(e => 
     e.products = e.products.filter(p => p.qty)
  );

我需要一种变通方法或其他方法才能使它在所有浏览器中都能正常工作。请帮忙。

1 个答案:

答案 0 :(得分:1)

IE-10不支持此方法。您应该使用jQuery.grep()而不是filter()方法。

e.products = jQuery.grep(e,(p => p.qty))