简体   繁体   中英

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?

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"] . 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"; line, it does not change the name of the property on 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"; line (just like it is in any other expression).

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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