简体   繁体   中英

Null Values in array of objects

I am creating objects when textbox having some values (using ng-blur and textbox.value!==undefined ) and then putting these objects in an array (all working fine here).

When I click on checkbox (checkbox model bind with textbox ng-required) I need to delete that particular object having that textbox value. I am using:

arr.splice(index,1);

to remove that particular object from array (by matching it's name like "monthly" or "quarterly" etc.), but it is creating null at that particular position.

for eg [object,object,object]

[
{name:"monthly",
  amount:1000 },

{name:"quarterly",
  amount:1200 },

{name:"yearly",
  amount:1300 }
]

after removing all element it shows [] and when I add another new object it displays [3:object] and it's content as [null,null,null,object];

or

if I remove middle object say name:"quarterly", it shows [object,object] but after adding a new object it display array as [object,object,null,object] with length of array as 4.

Why is there null and how can I remove that from array. (don't want to iterate again to check null ).

It is difficult to say why your code creates the null values without have a look to it.

But I can say you that it is not the expected behaviour.

You can see this example to get some inspiration:

 var data = [ {name:"monthly", amount:1000 }, {name:"quarterly", amount:1200 }, {name:"yearly", amount:1300 } ]; var newObjectToBeAdded = { name: "daily", amount:"100" } function showObjects() { document.body.innerHTML += data + '<hr>'; } function deleteObjectByName( objectName ) { for( var i = 0; i < data.length; i++ ) { if( data[ i ].name == objectName ) { data.splice(i, 1); } } } function addObjectToData( newObject ) { data.push( newObject ); } showObjects(); deleteObjectByName( "quarterly" ); showObjects(); addObjectToData( newObjectToBeAdded ); showObjects(); 

Just to throw a guess out, maybe you are accidentally duplicating the array. Maybe in some point of your code you are doing something like this:

var new_array = original_array.splice( index );

Or creating the new array in the loop you use to find the target object, or using some kind of intermediate array, etc.

Hope it helps!

var arrayWithoutNulls = myArray.filter(function(val) {
    if (val) {
        return val;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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