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;

console.log(verts.A)

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

问题评论:

1  
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 stackoverflow.com/questions/9907419/…
    
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) jsfiddle.net/3amo87zm any ideas welcome
– Nick
1 hour ago

答案:

答案1:

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

原文地址:

https://stackoverflow.com/questions/47754136/how-can-i-display-the-key-of-an-accessed-object-in-javascript

添加评论