admin管理员组文章数量:1135173
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 Abe
which has an index of A
. How can I do something along the lines of myobj[0]
and get out "Abe".
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 Abe
which has an index of A
. How can I do something along the lines of myobj[0]
and get out "Abe".
9 Answers
Reset to default 115I know it's a late answer, but I think this is what OP asked for.
myobj[Object.keys(myobj)[0]];
JS objects have no defined order, they are (by definition) an unsorted set of key-value pairs.
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]];
myobj = {"A":["Abe"], "B":["Bob"]}
Object.keys(myobj)[0]; //return the key name at index 0
Object.values(myobj)[0] //return the key values at index 0
You could try
Object.entries(myobj)[0]
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
myobj.A
------- or ----------
myobj['A']
will get you 'B'
Try:
const obj = {
name: 'John Doe',
age: 34,
country: 'Switzerland',
};
var _key = Object.keys(obj)[0]
var _value = Object.values(obj)[0]
var key = Object.entries(obj)[0][0]
var value = Object.entries(obj)[0][1]
console.log(_key)
console.log(_value)
console.log(key)
console.log(value)
$.each(myobj, function(index, value) {
console.log(myobj[index]);
});
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.
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"]
本文标签: javascriptGet element of JS object with an indexStack Overflow
版权声明:本文标题:javascript - Get element of JS object with an index - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736921964a1956490.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
B
is important here? – Eric Commented Feb 10, 2013 at 20:59