How can I display the key of an accessed object in javascript


I would like to be able to get and use the key of a selected object in js

Lets say I have the following object that contains other objects

verts = { A: {x: 7.5, y: 0, z: -7.5}, B: {x: 0, y: 0, z: -15 }

If I can access item A for example with the following;


It will show me the value within the object (i.e. x: 7.5, y: 0, z: -7.5) but I do not know how to access the selected objects key i.e. in this case “A”. I would like to be able to store it as a variable for use as a string later on. It feels like I should be able to write this.key or this[key] somewhere somehow but I cannot find an appropriate answer on here. I am using jquery so if there is a quick way using that thank you.

Thanks for any advice as ever


What do you mean by “selected object”? Please provide an example of some code where there is a selected object.
Thanks JLRishe maybe I am using the wrong terminology but if you look at my example, I access the value of verts.A by logging it to the console but I can only see the value of verts.A and not the key i.e. A
– Nick
2 hours ago
Probably you may find relevant here…
The key isn’t part of the object, so in general, you can’t get the key from the object. Could you provide an example of a situation where you need this? There’s probably another way to accomplish it.
Hi JLRishe, thanks, Ok at the below fiddle there is some illustrative code (ie it does not work but shows the kind of thing I would like to achieve) any ideas welcome
– Nick
1 hour ago



Once you’ve read an object using a key, there is no longer a link back to the key you used.

The best thing you can do is store the key you’re using in a variable and then use square bracket notation to read it:

var verts = { A: {x: 7.5, y: 0, z: -7.5}, B: {x: 0, y: 0, z: -15 } };
var key = 'A';
var result = verts[key];

console.log(key, result);

Another option is to run your initial object through a pre-processor to build this link:

function preProcess(input){
    return Object.keys(input).reduce( function(p,c){
      var newObj = input;
      newObj._key = c;
      p = newObj
      return p

var verts = { A: {x: 7.5, y: 0, z: -7.5}, B: {x: 0, y: 0, z: -15 } };
var vertsWithKeys = preProcess(verts);

var item = verts.A;
console.log(item._key, item);


Thanks Jamiec – I wondered if that might be the case, maybe I have the only use case for it but it seems like something it would be good to be able to do
– Nick
2 hours ago
@Nick see update. Its less than ideal IMO but serves your requirement.
Thanks Jamiec, its not quite as succinct as I had hoped but it works so thank you
– Nick
2 hours ago