使用jQuery过滤嵌套的JSON以获取空值

时间:2018-10-06 18:52:33

标签: javascript

我有一个嵌套的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方法过滤数据并删除空白的object,以便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"
   }
}

请帮助。

1 个答案:

答案 0 :(得分:2)

这是一种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);