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
4 Answers
Reset to default 4Thsi 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
版权声明:本文标题:javascript - jQuery - delete last object by key - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744343762a2601635.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论