Use key's value as key in key-value pair in Javascript

邮差的信 提交于 2019-12-20 07:36:36

问题


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"};

回答1:


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, e.g. foo.bar, or using bracketed notation and a string, e.g. 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).




回答2:


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



回答3:


To get the value for a given key on an object use object["key"] or object.key



来源:https://stackoverflow.com/questions/14103212/use-keys-value-as-key-in-key-value-pair-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!