user5405873
user5405873

Reputation:

how to remove [object object] based on value not based on key

I want to remove all [object object] from my json not based on key but based on value i,e ([object object]).

here is my json

var allProductSpecification = {
            "Vinyl_Backlite": [{
              "Price": "280",
              "Quantity": "1",
              "Amount": "280"
            }],
            "Steel": [{
              "Price": "18",
              "Quantity": "1",
              "Amount": "18"
            }],
            "0": "[object Object]",
            "1": "[object Object]"
          }
   
   allProductSpecification = JSON.parse(allProductSpecification);
   
   delete  allProductSpecification[0];
   
    delete  allProductSpecification[1];
   
   console.log(allProductSpecification);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

here is how i have removed a [object object] from key:0

delete  allProductSpecification[0];

Question: how can i do it for any number of [object object] dynamically

Upvotes: 0

Views: 216

Answers (2)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

If you do have a JSON string (not javascript object literal as you have posted as example). Then you could use custom reviver with JSON.parse

const json = `{
            "Vinyl_Backlite": [{
              "Price": "280",
              "Quantity": "1",
              "Amount": "280"
            }],
            "Steel": [{
              "Price": "18",
              "Quantity": "1",
              "Amount": "18"
            }],
            "0": "[object Object]",
            "1": "[object Object]"
          }`;
          
const obj = JSON.parse(json, (key, value) => (value === {}.toString() ? undefined : value))

console.log(obj)

Upvotes: 1

Hassan Imam
Hassan Imam

Reputation: 22524

You can use array#reduce with the condition to add only those key whose value is not [object Object].

var allProductSpecification = { "Vinyl_Backlite": [{ "Price": "280", "Quantity": "1", "Amount": "280" }], "Steel": [{ "Price": "18", "Quantity": "1", "Amount": "18" }], "0": "[object Object]", "1": "[object Object]" },
    result = Object.keys(allProductSpecification).reduce((r,k) => {
      if(allProductSpecification[k] !== '[object Object]')
        r[k] = allProductSpecification[k];
      return r;
    },{});
    
console.log(result);

Upvotes: 2

Related Questions