0

I have an array of objects like this:

(2) [{…}, {…}]
0: {type: "", label: "first name", title: "", name: "sa", uniquekey: "", …}
1: {type: "text", label: "first name", title: "", name: "asdasd", uniquekey: "", …}
lastIndex: (...)
lastItem: (...)
length: 2
__proto__: Array(0)

This data is being received from parent component.

Also, in my react state,

this.state = {
  data: this.props.newdata,
  formname: '',
  finalData: {}
}

What I am trying to achieve is when I click a onChange() field handler in child component, it sets a value for state formname. The on clicking form onSubmit() handler, I want to merge both formname and data state into state finalData in the form of an object.

I tried using using map() like this, but got confused:

onSubmit = (e) => {   
      e.preventDefault();
      console.log('TEST FORM', this.state.data);
      console.log('TEST FORM NAME', this.state.formname);

      // console.log(this.setState({
      //   newform: [...this.state.newform, this.state.formname]
      // }), 'added form name');

      var finalData = this.state.data.map((item, i) => {
        return {
          form: item
        };
      });
      console.log(formField);

      this.setState({ finalData:finalData })
} 

I want to look it something like this:

{
   0:{
     formname1:'',
     [ 0: {a:'', b:''},
       1: {a:'', b:''},
     ]
   },
   1:{
     formname2:'',
     [ 0: {a:'', b:''},
       1: {a:'', b:''},
     ]
   },
.......
}

Kindly help out

7
  • How exactly looks your data structure before and how should it look afterwards? It's not clear, what you want to merge Commented Nov 14, 2019 at 13:08
  • @ssc-hrep3 updated. Kindly check Commented Nov 14, 2019 at 13:36
  • @bubble-cord, this is not an object. Where is the key for the array. Commented Nov 14, 2019 at 13:39
  • Question is not clear. formname1 and formname2 are not a part of initial state. Where are they coming from? Do you mind editing the state? Commented Nov 14, 2019 at 13:43
  • I want it to get stored into an object Commented Nov 14, 2019 at 13:43

3 Answers 3

1
const finalData = {...this.state.data, formname: this.state.formname};

or

const finalData = {[this.state.formname]: this.state.data};

?

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

3 Comments

If I add multiple data with different form names like 'form1' and then 'form2' in addition to their data, it only stores 'form2' and corresponding data, over-riding form1
Your state has formname outside the data array.
That's what I need to do. Add state formname along with data array into a new single object everytime on each click, so that they appear as single data.
1

Should it be something like this?

this.setState(prevState => ({
    finalData: [
        ...prevState.finalData,
        {
            formname: this.state.formname,
            data: [...this.state.data]
        }
    ]
}));

Comments

1

I did'nt understand your exact question. I am making an assumption that the formname is stored in this.state.formname and the array is stored in this.state.data. The required object can be easily generated as below:

onSubmit = (e) => {   

  e.preventDefault();

  // Cloning the finalData Object from state. You do not want to mutate directly
  const finalDataClone =  {...this.state.finalData};


   //Now push the dynamic object to the clone. 
   //The numbers that you mentioned in your example object are dynamically generated here based on object length.

  var objSize = Object.keys(finalDataClone).length;

  finalDataClone[objSize] = {
          [`formName${objSize-1}`] : this.state.formname,
          dataArray : {...this.state.data}
  }


 // Set the state here
      this.setState((prevState)=>{
        return {
           finalData : finalDataClone
        }
      })

} 

So, above basically generates dynamic key value pairs.

Also, just for your information, since setState() is async operation, React recommends to use updater function inside the setState()

1 Comment

If you feel this answer as correct, you can accept this as answer.

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.