Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjusting object keys after deleting key [duplicate]

In Javascript, I have an array of objects like so:

var array = [{ foo: 'bar' }, { foo: 'baz' }, { foo: 'qux' }];

which looks like this, really...

[0: {...}, 1: {...}, 2: {...}]

and I delete the second one:

delete array[1];

then I have this:

[0: {...}, 2: {...}]

How can I adjust this array so the keys are back in numerical order?

like image 366
Jason Varga Avatar asked Mar 19 '14 23:03

Jason Varga


2 Answers

I believe Array.splice is what you are looking for in this case

array.splice(1,1);
like image 152
steven Avatar answered Sep 23 '22 21:09

steven


Use the splice method instead:

array.splice(1, 1);

Will remove 1 object at index 1, without leaving an empty space.

like image 30
Adrian Norman Avatar answered Sep 21 '22 21:09

Adrian Norman