简体   繁体   English

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

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

I'm trying to remove an object from Json Object it works..but it replace it with null..i dont know why, how can i remove the null value from the json..heres the function : 我正在尝试从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));
    };

heres the object: 继承人的对象:

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

You can use filter() , x will be without null's. 你可以使用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;
}

fiddle 小提琴

There are multiple ways to delete an object from an array of objects in JavaScript. 有多种方法可以从JavaScript中的对象数组中删除对象。 You don't need AngularJS for that, you can use VanillaJS. 你不需要AngularJS,你可以使用VanillaJS。

If you just want the nulls filtered you can use 如果您只想过滤掉空值,可以使用

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

But this loses the original reference to your object. 但这会丢失对您对象的原始引用。

If you want to keep the reference, Use array.splice(). 如果要保留引用,请使用array.splice()。

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

now you will have null less array in yourArray. 现在你将在yourArray中使用null less数组。 This actually deletes an object from an array without changing the reference, 这实际上是在不更改引用的情况下从数组中删除对象,

delete will replaced the object with undefined delete将使用undefined替换该对象

You can filter the array to remove them using Array#filter() 您可以使用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