3

Below is the json :

var data= {
    'A' : {
        'Total' : 123,
        'Cricket' : 76,
        'Football' : 12,
        'Hockey' : 1,
        'None' : 10
    },
    'B' : {
        'Total': 123,
        'Cricket': 76,
        'Football': 12,
        'Hockey': 1,
        'None': 10
    },
    'C' : {
        'Total': 0,
        'Cricket': 76,
        'Football': 12,
        'Hockey': 1,
        'None': 10
    }   
}

I want to remove C in which value of total is zero,,

$.each(json, function (key, value) {
    if (value.Total === 0) {
        //delete
    }
});

I have tried various ways but didnt work

7
  • use delete json[key]. It will delete that object. Commented Jun 28, 2017 at 5:50
  • really? delete[key] ? are you sure of that syntax? Commented Jun 28, 2017 at 5:50
  • 1
    by the way, that's not JSON, that's just a javascript object, if it were JSON, you'd have to JSON.parse it before doing anything more Commented Jun 28, 2017 at 5:51
  • 1
    More so, it's not an array of objects either. Commented Jun 28, 2017 at 5:52
  • Looks like a duplicate of https://stackoverflow.com/questions/208105/how-do-i-remove-a-property-from-a-javascript-object Commented Jun 28, 2017 at 5:56

2 Answers 2

6

Use delete keyword to delete a property in an object.

var json = {
  'A': {
    'Total': 123,
    'Cricket': 76,
    'Football': 12,
    'Hockey': 1,
    'None': 10

  },
  'B': {
    'Total': 123,
    'Cricket': 76,
    'Football': 12,
    'Hockey': 1,
    'None': 10
  },
  'C': {
    'Total': 0,
    'Cricket': 76,
    'Football': 12,
    'Hockey': 1,
    'None': 10
  }
}

$.each(json, function(key, value) {
  if (value.Total === 0) {
    delete json[key];
  }
});

console.log(json);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

Comments

0
$(function(){


var data=    {
        'A' : {
            'Total' : 123,
            'Cricket' : 76,
            'Football' : 12,
            'Hockey' : 1,
            'None' : 10

        },
    'B' : {
        'Total': 123,
        'Cricket': 76,
        'Football': 12,
        'Hockey': 1,
        'None': 10
    },
    'C' : {
        'Total': 0,
        'Cricket': 76,
        'Football': 12,
        'Hockey': 1,
        'None': 10
    }   
}

 $.each(data, function (key, value) {

              if (value.Total === 0) {
                 delete data[key];
              }
});

console.log(data);

});

Fiddle: http://jsfiddle.net/ef3Le1en/

Comments

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.