我有一个嵌套的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"
}
}
请帮助。
答案 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);