繁体   English   中英

如何使用AngularJS从JSON对象中删除null?

[英]How can I remove null from JSON object with AngularJS?

我正在尝试从Json对象中删除一个对象它工作..但它用null替换它..我不知道为什么,我怎样才能从json中移除null值...函数:

company.deleteExternalLinkFromGrid = function (row, matricule) {
        // console.log('Inside of deleteModal, code = ' + code);
        //$scope.sitting= {};
       console.log(matricule);
        //console.log(JSON.stringify(linkJsonObj));
        delete linkJsonObj[matricule];

        console.log(JSON.stringify(linkJsonObj));
    };

继承人的对象:

[{ “名称”: “XXX”, “链接”: “www.ddd.com”, “ID”:0, “$$ hashKey”: “uiGrid-001Z”},NULL,NULL]

你可以使用filter()x将没有null。

function test()
{
    var x =[{"name":"xxx","link":"www.ddd.com","id":0,"$$hashKey":"uiGrid-001Z"},null,null].filter(isNotNull);
    alert(JSON.stringify(x));

}

function isNotNull(value) {
  return value != null;
}

小提琴

有多种方法可以从JavaScript中的对象数组中删除对象。 你不需要AngularJS,你可以使用VanillaJS。

如果您只想过滤掉空值,可以使用

var yourArray =[{"name":"xxx","link":"www.ddd.com","id":0,"$$hashKey":"uiGrid-001Z"},null,null];
     yourArray = yourArray.filter(function(elt){
     return elt != null;
    });

但这会丢失对您对象的原始引用。

如果要保留引用,请使用array.splice()。

  yourArray.forEach(function(){ 
      yourArray.splice(yourArray.indexOf(null),1);
  });   

现在你将在yourArray中使用null less数组。 这实际上是在不更改引用的情况下从数组中删除对象,

delete将使用undefined替换该对象

您可以使用Array#filter()过滤数组以删除它们

 var array = [{ "name": "xxx", "link": "www.ddd.com", "id": 0, "$$hashKey": "uiGid-001Z" }, { "name": "xx", "link": "www.dddcom", "id": 1, "$$hashey": "uiGrid-0029" }, { "name": "xxx", "link": "www.ddd.com", "id": 2 }]; delete array[1]; array = array.filter(a=>a); console.log(JSON.stringify(array)); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM