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

前端 未结 3 885
天涯浪人
天涯浪人 2021-01-28 16:14

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         


        
相关标签:
3条回答
  • 2021-01-28 16:29

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

    0 讨论(0)
  • 2021-01-28 16:41

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

    0 讨论(0)
  • 2021-01-28 16:46
    var gizmos = {gizmo1: "G1"};
    var things = {};
    things[gizmos.gizmo1]="T1";
    
    0 讨论(0)
提交回复
热议问题