首页 > 解决方案 > 从 json 中删除元素,而不添加 null

问题描述

我有以下 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":""}]

我正在使用此代码通过 id 从中删除一个元素:

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

但它返回一个带有 null 值的 json,如下所示:

[{"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]

有没有办法在没有空值的情况下返回它?

标签: jqueryjson

解决方案


你可以这样做:

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

请注意,您id是一个字符串("id":"13")

演示

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>


推荐阅读