0

I have a nested JSON which looks like this:

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

The qty key can have empty values in the object. I want to filter the data with jQuery method and remove the object with blank qty so the JSON can look like this -

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

Please help.

1 Answer 1

2

Here's a filter approach which mutates the object in-place:

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

Sign up to request clarification or add additional context in comments.

3 Comments

Note that this does not use jQuery nor should it.
Its giving me error in Internet explorer for this - unfilteredJSON.payload.keyData.forEach(e => e.products = e.products.filter(p => p.qty) );
It's probably the arrow functions. You can replace =>s with function (e) { ... }.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.