Dave
Dave

Reputation: 85

Accessing value in using key indexing

Suppose I have the dictionary dict = {'a': 1, 'b': 2, 'c': 3}, how could I get the value of a by index like dict[0] or getting dict[1] = 2 without using the explicite key? In fact, I would like to pass through that dictionary with a for loop in using index instead of explicit keys.

Upvotes: 3

Views: 51

Answers (3)

Pratheesh M
Pratheesh M

Reputation: 1078

Object.keys(dict).map((key)=>{
console.log(dict[key])
})

Here we can go through all the keys in the object. And we can get the value of a particular key using object[key].

Upvotes: 3

Rajesh
Rajesh

Reputation: 24925

Objects are Key - value pairs. These keys can be inserted/removed in any order. This makes using index to fetch keys inconsistent.

Also, properties of an object are not sorted in a particular order. So you cannot guarantee specific sequence to fetch using index.

Plus, you can have dynamic insertion/ deletions. So that will affect index based fetching.

All in all, its a bad idea to use Objects in this manner.

If you wish to use index based retrieval, you should use Arrays.

Reference:

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122008

No you cannot. key value pairs are unordered inside the object. If you want to just ignore the key and care about positioning of value, you doesn't need objects and you need Arrays.

Upvotes: 0

Related Questions