Is there any way to dynamically add JSON fields in Javascript?

Viewed 173
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 });
        });

I just want to store the array in json file with dynamic field name in element i.e. element should be the replaced with the value from the upper loop.

1 Answers

If your key is dynamic they you can do this way. [element] is way you can handle dynamic keys.

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 you can go through small blog which explains how you can set dynamic keys to json object.

Related