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

不想你离开。 提交于 2019-12-02 08:59:55

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).

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

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

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