EN
JavaScript - get element from object by index
1 answers
0 points
How to get element from object by index?
Let's say I have the following object:
xxxxxxxxxx
1
var myObject = {
2
a: ['aaa'],
3
b: ['bbb'],
4
};
and I need to get the first element of it.
How can I do something like myObject[0]
to get the 'aaa'
value?
1 answer
0 points
You can use Object.keys()
method to get array of the object's keys and then using array notation ([]
) you can access them by index like:
xxxxxxxxxx
1
myObject[Object.keys(myObject)[0]];
Practical example
xxxxxxxxxx
1
var myObject = {
2
a: ['aaa'],
3
b: ['bbb', 'bb', 'b'],
4
};
5
6
var aValues = myObject[Object.keys(myObject)[0]];
7
var bValues = myObject[Object.keys(myObject)[1]];
8
9
console.log(aValues); // [ 'aaa' ]
10
console.log(bValues); // [ 'bbb', 'bb', 'b' ]
Note:
Because you have arrays under
a
andb
key, theaValues
andbValues
will also be arrays. Going further, you may access individual elements like:xxxxxxxxxx
1bValues[0]; // 'bbb'
2bValues[1]; // 'bb'
3bValues[2]; // 'b'
References
0 commentsShow commentsAdd comment