【问题标题】:Is there any way to dynamically add JSON fields in Javascript?有没有办法在 Javascript 中动态添加 JSON 字段?
【发布时间】:2021-10-17 08:46:00
【问题描述】:
const demo = {
      data:[]
    };    
this.state.lossGroup.forEach(element => {
          const z= []
          this.state.selectedExposure.map((e) => {
            console.log(element,e.hazard_index.type )
            if (element == e.hazard_index.type) {
              z.push(e.id)
            }
          })
           demo.data.push({ element: z });
        });

我只想将数组存储在 json 文件中,元素中具有动态字段名称,即 element 应该替换为来自上部循环的值。

【问题讨论】:

  • 你的json是哪个变量?你能分享你的json的价值吗?
  • 我已经编辑了json变量,请检查一下。
  • 你能分享更多信息吗?你想用 json 文件做什么? this.state.selectedExposure 是否包含信息?是否要从演示对象创建 json?
  • 需要更多关于显示的代码结果与预期不同的具体细节
  • 我必须处理 this.state.lossGroup 中的“元素”。 “元素”值类似于 ['elem1','elem2','elem3 ']。我希望这些值作为 JSON 文件“演示”中的字段名称

标签: javascript arrays reactjs json


【解决方案1】:

如果您的密钥是动态的,您可以这样做。 [element] 是处理动态键的方式。

const demo = {
      data:[]
    };    
this.state.lossGroup.forEach(element => {
          const z= []
          this.state.selectedExposure.map((e) => {
            console.log(element,e.hazard_index.type )
            if (element == e.hazard_index.type) {
              z.push(e.id)
            }
          })
           demo.data.push({ [element] : z });
        });

here你可以浏览一个小博客,它解释了如何为 json 对象设置动态键。

【讨论】:

    猜你喜欢
    • 2021-05-24
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 2021-12-18
    • 2021-11-09
    • 2022-10-01
    • 1970-01-01
    • 2021-01-07
    相关资源
    最近更新 更多