Question

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"};
Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top