首页 > 解决方案 > 有没有办法在 Javascript 中动态添加 JSON 字段?

问题描述

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 文件中,元素中具有动态字段名称,即元素应替换为上循环中的值。

标签: javascriptarraysreactjsjson

解决方案


如果您的密钥是动态的,您可以这样做。 [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 });
        });

在这里,您可以浏览小型博客,该博客解释了如何为 json 对象设置动态键。


推荐阅读