3

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.

Dave
  • 85
  • 9
  • Use a Map. It will be sorted after insertion time, you can do `.values()[2]` ... – Jonas Wilms Nov 09 '17 at 07:02
  • Object is not suited for such operations. You can use `Object.Keys` to get keys and the loop like an array, but properties in object are not sorted in a specific order. So you cannot guarantee the order of keys and access using it – Rajesh Nov 09 '17 at 07:03
  • Make an answer @Rajesh maybe – Dave Nov 09 '17 at 07:05

3 Answers3

3
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].

Pratheesh M
  • 719
  • 3
  • 10
0

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.

Suresh Atta
  • 114,879
  • 36
  • 179
  • 284
0

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:

Community
  • 1
  • 1
Rajesh
  • 21,405
  • 5
  • 35
  • 66