2
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.

5
  • Which variable is your json? Can you share the value of your json? Commented Aug 14, 2021 at 13:02
  • I have edited json variable please check it. Commented Aug 14, 2021 at 13:06
  • Can you share some more information? What are you trying to do with the json file? Does this.state.selectedExposure contain information? Do you want to create json from the demo object? Commented Aug 14, 2021 at 13:10
  • Need more specific details about how results from code shown differ from expected Commented Aug 14, 2021 at 13:12
  • I have to deal with the "element" from the this.state.lossGroup. The "element" values are like ['elem1','elem2','elem3']. And I want these value as field name in JSON file "demo" Commented Aug 14, 2021 at 13:17

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.