Reputation: 9545
How do you identify an object by its place in the object.
myObj.b = 2
can I go somethiong like myObj[1] to show 2 also
?
var myObj = {
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: 6
}
Upvotes: 1
Views: 135
Reputation: 318498
No, this is not possible. An object property has no position as objects are not ordered.
You have to choose between:
[0..length)
, in order.A possible workaround would be creating both an object and an array and then using the object for key-based access and the array for index-based. You could then use the array to get the index(es) for a given value.
Upvotes: 8
Reputation:
No, myObj[1] will result in undefined. Object literals are hash maps (key, value stores), which do not support indexed based access. This is so because items in a hash do not have a predictable order of iteration.
What you can do, to get the flavor of an index going with your object fields, is:(in jQuery)
$.each(myObj, function(index, element) {
console.log(index + ' : ' + element)
});
In plain javascript, you could iterate over the fields using a for in loop, as shown:
for (key in myObj) {
console.log(key);
console.log(myObj[key]);
}
(Note: Your literal has syntax errors).
Upvotes: 2