Javascript 获取带有索引的 JS 对象元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14802481/
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
Get element of JS object with an index
提问by ChapmIndustries
Ok so let's say that I have my object
好吧,让我们说我有我的对象
myobj = {"A":["Abe"], "B":["Bob"]}
and I want to get the first element out of it. As in I want it to return Abewhich has an index of A. How can I do something along the lines of myobj[0]and get out "Abe".
我想从中取出第一个元素。正如我希望它返回Abe索引为A. 我怎么能像myobj[0]“安倍”那样做一些事情。
回答by Reinis
I know it's a late answer, but I think this is what OP asked for.
我知道这是一个迟到的答案,但我认为这就是 OP 要求的。
myobj[Object.keys(myobj)[0]];
回答by Alnitak
JS objects have no defined order, they are (by definition) an unsortedset of key-value pairs.
JS 对象没有定义的顺序,它们(根据定义)是一组未排序的键值对。
If by "first" you mean "first in lexicographical order", you can however use:
如果“第一”是指“按字典顺序排列的第一”,则可以使用:
var sortedKeys = Object.keys(myobj).sort();
and then use:
然后使用:
var first = myobj[sortedKeys[0]];
回答by Dennis Paixao
Object.keys(city)[0]; //return the key name at index 0
Object.values(city)[0] //return the key values at index 0
回答by doset
var myobj = {"A":["Abe"], "B":["Bob"]};
var keysArray = Object.keys(myobj);
var valuesArray = Object.keys(myobj).map(function(k) {
return String(myobj[k]);
});
var mydata = valuesArray[keysArray.indexOf("A")]; // Abe
回答by Fahem Idir
I Hope that will help
我希望这会有所帮助
$.each(myobj, function(index, value) {
console.log(myobj[index]);
)};
回答by Jeffpowrs
myobj.A
------- or ----------
- - - - 或者 - - - - -
myobj['A']
will get you 'B'
会给你'B'
回答by jfriend00
If you want a specific order, then you must use an array, not an object. Objects do not have a defined order.
如果你想要一个特定的顺序,那么你必须使用一个数组,而不是一个对象。对象没有定义的顺序。
For example, using an array, you could do this:
例如,使用数组,您可以这样做:
var myobj = [{"A":["B"]}, {"B": ["C"]}];
var firstItem = myobj[0];
Then, you can use myobj[0] to get the first object in the array.
然后,您可以使用 myobj[0] 获取数组中的第一个对象。
Or, depending upon what you're trying to do:
或者,取决于您要执行的操作:
var myobj = [{key: "A", val:["B"]}, {key: "B", val:["C"]}];
var firstKey = myobj[0].key; // "A"
var firstValue = myobj[0].val; // "["B"]

