简体   繁体   English

在Javascript中使用键值作为键值对中的键

[英]Use key's value as key in key-value pair in Javascript

How can you use the value of a key-value pair as the key in a different key-value pair in javascript? 如何在JavaScript中将键值对的值用作另一个键值对中的键?

I'd like to do the following: 我想做以下事情:

var gizmos = {gizmo1: "G1"};
var things = {gizmos.gizmo1: "T1"};

So that things essentially equals: 因此,本质上是相等的:

var things = {"G1": "T1"};

Like this: 像这样:

var gizmos = {gizmo1: "G1"};
var things = {};
things[gizmos.gizmo1] = "T1";

There's no way to do it as part of the object initializer (aka object "literal"), you have to do it after. 作为对象初始值设定项(也称为对象“文字”)的一部分,无法执行此操作,您必须在之后执行。

The reason it works is that in JavaScript, you can access (get or set) a property on an object in two ways: Either using dotted notation and a literal , eg foo.bar , or using bracketed notation and a string , eg foo["bar"] . 它起作用的原因是,在JavaScript中,您可以通过两种方式访问​​(获取或设置)对象上的属性:使用点分符号和文字 (例如foo.bar ,或使用方括号和字符串 (例如foo["bar"] In the latter case, the string doesn't have to be a string literal, it can be the result of any expression (including, in this case, a property lookup on another object). 在后一种情况下,字符串不必是字符串文字,它可以是任何表达式的结果(在这种情况下,包括在另一个对象上的属性查找)。


Side Note: If you change gizmos.gizmo1 after you do the things[gizmos.gizmo1] = "T1"; 注意:如果在执行gizmos.gizmo1更改 gizmos.gizmo1 ,则things[gizmos.gizmo1] = "T1"; line, it does not change the name of the property on things . 行,它不会更改things的属性名称。 There's no enduring link, because the value of gizmos.gizmo1 was used to determine the property name during the things[gizmos.gizmo1] = "T1"; 没有持久的链接,因为在things[gizmos.gizmo1] = "T1";期间,使用gizmos.gizmo1来确定属性名称things[gizmos.gizmo1] = "T1"; line (just like it is in any other expression). 行(就像在其他任何表达式中一样)。

var gizmos = {gizmo1: "G1"};
var things = {};
things[gizmos.gizmo1]="T1";

要获取对象上给定键的值,请使用object["key"]object.key

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

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