Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Javascript object item adding null value [duplicate]

Tags:

javascript

I have an javscript object

finalTitleList =[{"Title":"ffd","Iscompleted":"","Id":0},
                 {"Title":"fdfmdbk","Iscompleted":"","Id":1},
                 {"Title":"fdf,d","Iscompleted":"","Id":2}]

Suppose i like to delete an 2nd item using delete finalTitleList[1], after deletion it delete the item but length is not updated(snapshot attached: contain only 2 item but showing length 3).

So when i am adding that object in localstorage using

localStorage.setItem("TaskTitleList16", JSON.stringify(finalTitleList));

On place of deleteditem it shows null.

I want to completely remove that item, please help me.

like image 726
Sahil Gupta Avatar asked Jan 18 '15 02:01

Sahil Gupta


1 Answers

You're wanting Array.prototype.splice().

This is an example of usage:

var a = [1, 2, 3, 4, 5]; 
a.splice(2,1); // Being splice at element 2, deleting (and returning) 1 element
console.log(a); // outputs [1, 2, 4, 5]

Delete works a little differently than you may expect with arrays, and shouldn't really be used. For one, delete doesn't affect the length of the array. For two, it leaves this undefined value in the middle of the array, which means you'll have to deal with it in code using the array.

In summary, don't use delete on arrays. There's a ton of built-in methods that you can use to work with arrays, or compose together into your own operations. Use them.

like image 110
jdphenix Avatar answered Oct 20 '22 17:10

jdphenix