获取 javascript 对象中的最后一项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4317456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:52:40  来源:igfitidea点击:

getting the last item in a javascript object

javascriptobject

提问by sprugman

If I have an object like:

如果我有一个对象,例如:

{ 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' }

If I don't know in advance that the list goes up to 'c', other than looping through the object, is there a way to get the last item in the object (e.g. 'carrot')?

如果我事先不知道列表上升到 'c',除了循环遍历对象,有没有办法获取对象中的最后一项(例如'carrot')?

采纳答案by Alex

No. Order is not guaranteed in JSON and most other key-value data structures, so therefore the last item could sometimes be carrotand at other times be bananaand so on. If you needto rely on ordering, your best bet is to go with arrays. The power of key-value data structures lies in accessing values by their keys, not in being able to get the nthitem of the object.

不。在 JSON 和大多数其他键值数据结构中不能保证顺序,因此最后一项有时可能是carrot,有时是banana,依此类推。如果您需要依赖排序,最好的办法是使用数组。键值数据结构的强大之处在于通过它们访问值keys,而不是能够获取nth对象的项。

回答by Kristina Stefanova

Yes, there is a way using Object.keys(obj). It is explained in this page:

是的,有一种方法可以使用Object.keys(obj). 在此页面对此进行了解释:

var fruitObject = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
Object.keys(fruitObject); // this returns all properties in an array ["a", "b", "c"]

If you want to get the value of the last object, you could do this:

如果你想获得最后一个对象的值,你可以这样做:

fruitObject[Object.keys(fruitObject)[Object.keys(fruitObject).length - 1]] // "carrot"

回答by user3282891

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

where obj is your object

其中 obj 是您的对象

回答by George

var myObj = {a: 1, b: 2, c: 3}, lastProperty;
for (lastProperty in myObj);
lastProperty;
//"c";

source:http://javascriptweblog.wordpress.com

来源:http: //javascriptweblog.wordpress.com

回答by ollazarev

Solution using the destructuring assignment syntax of ES6:

使用 ES6 的解构赋值语法的解决方案:

var temp = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
var { [Object.keys(temp).pop()]: lastItem } = temp;
console.info(lastItem); //"carrot"

回答by meder omuraliev

Use an array, not an object literal, if order matters.

如果顺序很重要,请使用数组,而不是对象字面量。

list = ['apple', 'banana', 'carrot'];

Or something like

或者类似的东西

dict = {
 'a' : ['apple', 'awesome'],
 'b' : ['best friend']
};

Or even..

甚至..

dict = [{letter:'a', list:['apple', 'awesome']},{letter:'b', list:['best friend']}];

The keys for dictare not guaranteed at all to be in order.

dict根本不能保证的键是有序的。

回答by MooGoo

As for the ordering of object properties in Javascript, I will just link to this answer:

至于 Javascript 中对象属性的排序,我将链接到这个答案:

Elements order in a "for (… in …)" loop

“for (... in ...)”循环中的元素顺序

Specifically:

具体来说:

All modern implementations of ECMAScript iterate through object properties in the order in which they were defined

ECMAScript 的所有现代实现都按照定义的顺序遍历对象属性

So every other answer here is correct, there is no official guaranteed order to object properties. However in practice there is (barring any bugs which naturally can screw up even set-in-stone officially specified behavior).

所以这里的每个其他答案都是正确的,没有官方保证的顺序来反对属性。然而,在实践中是有的(除非有任何错误,这些错误自然会破坏甚至一成不变的官方指定行为)。

Furthermore, the de-facto enumeration order of object properties is likely to be codified in future EMCAScript specs.

此外,对象属性的事实上的枚举顺序可能会编入未来的 EMCAScript 规范中。

Still, at this time I would not write code around this, mostly because there are no built-in tools to help deal with object property order. You could write your own, but in the end you'd always be looping over each property in an object to determine its position.

不过,此时我不会围绕这个编写代码,主要是因为没有内置工具来帮助处理对象属性顺序。您可以编写自己的,但最终您总是循环遍历对象中的每个属性以确定其位置。

As such the answer to your question is No, there is no way besides looping through an object.

因此,您的问题的答案是No,除了循环遍历对象之外别无他法。

回答by Shapon Pal

You can try this. This will store last item. Here need to convert obj into array. Then use array pop()function that will return last item from converted array.

你可以试试这个。这将存储最后一项。这里需要将 obj 转换为数组。然后使用数组pop()函数从转换后的数组中返回最后一项。

var obj = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };
var last = Object.keys(obj).pop();
console.log(last);
console.log(obj[last]);

回答by somebodysomewhere

The other answers overcomplicate it for me.

其他答案对我来说过于复杂。

let animals = {
  a: 'dog',
  b: 'cat',
  c: 'bird'
}

let lastKey = Object.keys(animals).pop()
let lastValue = animals[Object.keys(animals).pop()]

回答by Reha Ozenc

JSArray = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };  
document.write(Object.keys(JSArray)[Object.keys(JSArray).length-1]);// writes 'c'   
document.write(JSArray[Object.keys(JSArray)[Object.keys(JSArray).length-1]]); // writes 'carrot'