0

I have the following json :

var json_obj:
[{"id":"7","a_id":0,"cost":"Real Cost","desc":"this a value","minage":0,"maxage":""},
{"id":"10","a_id":0,"cost":"Real Cost","desc":"other","minage":0,"maxage":""},
{"id":"13","a_id":0,"cost":"Real Cost","desc":"other","minage":0,"maxage":""}]

I am using this code to remove an element from it by id :

jQuery.each(json_obj, function(i, val) {
  if(  val.id  === 13 ) // delete index
         {
          delete json_obj[i];
                   
          }
    });

but it return a json with null value like this :

[{"id":"7","a_id":0,"cost":"Real Cost","desc":"this a value","minage":0,"maxage":""},
{"id":"10","a_id":0,"cost":"Real Cost","desc":"other","minage":0,"maxage":""},
null]

is there a way to return it with out the null value ?

1 Answer 1

1

You could do it like this:

json_obj = jQuery.grep(json_obj, function(obj) {
  return obj.id != "13";
});

Please note that your id is a string ("id":"13")

Demo

var json_obj = [{
    "id": "7",
    "a_id": 0,
    "cost": "Real Cost",
    "desc": "this a value",
    "minage": 0,
    "maxage": ""
  },
  {
    "id": "10",
    "a_id": 0,
    "cost": "Real Cost",
    "desc": "other",
    "minage": 0,
    "maxage": ""
  },
  {
    "id": "13",
    "a_id": 0,
    "cost": "Real Cost",
    "desc": "other",
    "minage": 0,
    "maxage": ""
  }
]


json_obj = jQuery.grep(json_obj, function(obj) {
  return obj.id != "13";
});

console.log(json_obj)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

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.