简体   繁体   English

如何在JavaScript中显示已访问对象的键

[英]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 我希望能够获取和使用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; 如果我可以通过以下方式访问项目A;

console.log(verts.A)

It will show me the value within the object (ie x: 7.5, y: 0, z: -7.5) but I do not know how to access the selected objects key ie in this case "A". 它将向我显示对象内的值(即x:7.5,y:0,z:-7.5),但我不知道如何访问所选对象键,即在这种情况下为“ 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. 感觉我应该能够以某种方式编写this.key或this [key],但是我在这里找不到合适的答案。 I am using jquery so if there is a quick way using that thank you. 我正在使用jquery,所以如果有一种快速的使用方法,谢谢。

Thanks for any advice as ever 感谢您的任何建议

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[c]; newObj._key = c; p[c] = 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); 

You're making this more complicated than it has to be. 您正在使它变得比必须的更加复杂。 If you know at some point which keys you're using (and it seems you do), then all you need to do is ensure that those keys are passed along to whatever it is that needs them. 如果您在某个时候知道正在使用哪些密钥(似乎已经使用过),那么您要做的就是确保将这些密钥传递给需要它们的任何对象。

Like this: 像这样:

//vertices stored as objects
verts = { A: {x: 7.5, y: 0, z: -7.5}, B: {x: 0, y: 0, z: -15}, C: {x: 0, y: 0, z: -7.5} }

//make a triangle using accessed vertices
makeTriangle(verts, 'A', 'B', 'C')

function makeTriangle(vertices, key1, key2, key3){
    $("example").append('\
    <a-triangle\
        id="' + key1 + '_'+ key2 + '_'+ key3 + '"\
        vertex-a="' + vertices[key1](joined) + '"\
        vertex-b="' + vertices[key2](joined) + '"\
        vertex-c="' + vertices[key3](joined) + '"\
    </a-triangle>');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM