简体   繁体   English

JavaScript请求对象-将键作为变量转换为字符串

[英]JavaScript request object- convert key as a variable to string

I'm a programming beginner. 我是编程初学者。

API post call accepts object variable (derived from variable) as a string as follows API后期调用将对象变量(从变量派生)接受为字符串,如下所示

"option": 
    {           
  "235": “30”
},
 {           
    "238": “32”
}

My code angular 6 我的代码角度6

  option = [];
  ---

    this.option.push({
      [option.product_option_id]: $event
    });

which result 哪个结果

 option = [ {
   235: 30
 }]

but need this variable in double-quoted "235". 但需要将此变量括在双引号“ 235”中。

please help 请帮忙

but need this variable in double-quoted "235" 但需要在双引号“ 235”中使用此变量

By which you mean that you need it to be a string . 这表示您需要将其作为字符串

Don't worry, it is. 不用担心,是的。 When you use a number as a property name, it's converted to a string automatically. 当您使用数字作为属性名称时,它会自动转换为字符串。 Property names can only be strings or Symbols, so things that aren't strings or Symbols get converted to string: 属性名称只能是字符串或符号,因此不是字符串或符号的内容将转换为字符串:

 class Example { constructor() { this.option = []; const option = { product_option_id: 42 }; const $event = {}; this.option.push({ [option.product_option_id]: $event }); const pushed = this.option[0]; for (const key of Object.keys(pushed)) { console.log(`${key}: ${typeof key}`); } } } new Example(); 

That said, the expression within the [] of a computed property name is just that: an expression. 也就是说,计算出的属性名称的[]中的表达式就是:一个表达式。 So if you wanted to be explicit, you could use String there: 因此,如果要明确,可以在此处使用String

option.push({
  [String(option.product_option_id)]: $event
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM