【问题标题】:how to set json attribute using const value如何使用 const 值设置 json 属性
【发布时间】:2022-11-16 15:05:56
【问题描述】:

我想使用 const 数据制作 Json 属性 像这样。

const title = 'NAME'
data = {title: 'This is title'}
console.log(JSON.stringify(data))

我想要这个结果 => {名称:'这是标题'}

但这表明 => {标题:'这是标题'}

我应该怎么办?

【问题讨论】:

    标签: json


    【解决方案1】:

    对于动态密钥,您可以使用[variableName] 表示法。

    所以换title[title]

    const title = 'NAME'
    data = {[title]: 'This is title'}
    console.log(JSON.stringify(data))

    【讨论】:

    • 感谢您出人意料、迅速而准确的回复。祝你一直好运。
    • @naruen,很高兴为您提供帮助。
    猜你喜欢
    • 2021-09-05
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多