【问题标题】:is there a way in JavaScript to create an object where the object keys have the same name as the variables used for the value?JavaScript 中有没有一种方法可以创建一个对象,其中对象键与用于值的变量具有相同的名称?
【发布时间】:2021-02-07 02:52:26
【问题描述】:

类似于在 vuex 中使用 mapFunction(['name'])。

在学习 vuex 功能时,我遇到了它的 mapfunctions,它可以用相同的名称或不同的名称映射所需的属性。

我想实现一个相似之处,其中变量的名称和值分别作为键值对映射到对象。

在 vanilla javaScript 中已经可以了吗?

参考: vuex documentation vuex mapping guide article

ps:请查看参考资料以获得更清晰的功能说明

前->

`
  variable var_name1='var_value1'
  variable var_name2='var_value2'
  //note this is the format of the vuex where the name of a mapped property will remain the same      
  obj={[var_name1,var_name2]}

 
//the above should be equivalent to this
 obj={
       var_name1='var_value1',
       var_name2='var_value2',

   }


  

`

【问题讨论】:

    标签: javascript object variables mapping vuex


    【解决方案1】:

    const var_name1='var_value1'
    const var_name2='var_value2'
    
    const obj = {var_name1,var_name2}
    
    console.log(obj)
    console.log(obj.var_name1)
    console.log(obj.var_name2)

    【讨论】:

      猜你喜欢
      • 2010-10-05
      • 2018-12-30
      • 1970-01-01
      • 2013-06-16
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 2022-08-15
      • 2014-02-26
      相关资源
      最近更新 更多