admin管理员组

文章数量:1403369

Hi i have this object :

object {
 key1:[.....],
 key2:[....],
 key3:[.... ]
}

how does i can delete the last object key (key3)?

i would like to be free to delete last object key without knowing anything about that key.

Hi i have this object :

object {
 key1:[.....],
 key2:[....],
 key3:[.... ]
}

how does i can delete the last object key (key3)?

i would like to be free to delete last object key without knowing anything about that key.

Share Improve this question edited Mar 14, 2014 at 8:19 Filippo oretti asked Sep 26, 2011 at 0:40 Filippo orettiFilippo oretti 49.9k96 gold badges229 silver badges351 bronze badges 1
  • There is no such thing as the "last" key in an object. Object's don't keep track of the order of their keys. If you need to keep things in order, use an array. It may be most efficient to keep a separate array of just they keys, depending on your use case. – rjmunro Commented Nov 29, 2012 at 10:38
Add a ment  | 

4 Answers 4

Reset to default 4

Thsi is the ES5-patible way of doing it:

obj = {a : 1, b : 2, c : 3};

var k = Object.keys(obj);
delete obj[k[k.length-1]];

or shorter:

delete obj[Object.keys(obj)[Object.keys(obj).length-1]];

You can't assume that the last element added will be the last element listed in a javascript object. See this question: Elements order in a "for (… in …)" loop

In short: Use an array if order is important to you.

There is not "last" object key within an object in Javascript. Object keys are not ordered and hence, there cannot be first or last.

I guess, technically, the keys aren't in any specific order, but anyway...

var key;
for (key in obj);
delete obj[key];

It iterates over the whole object, and then deletes whatever was the last thing to be visited.

edit to illustrate

obj = {a : 1, b : 2, c : 3};

for (key in obj); // loops over the entire object, doing nothing *EXCEPT* 
                  // updating the `key` variable

alert(key); // "c" ... the last value of `key` was 'c'

delete obj[key];  // remove obj.c

本文标签: javascriptjQuerydelete last object by keyStack Overflow