我有一个像这样的对象数组:
(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)
此数据是从父组件接收的。
另外,在我的 react 状态下,
this.state = {
data: this.props.newdata,
formname: '',
finalData: {}
}
我想要实现的是,当我单击子组件中的 onChange()
字段处理程序时,它会为状态 formname
设置一个值。单击表单 onSubmit()
处理程序,我想将 formname
和 data
状态合并到状态 finalData
中物体的形式。
我尝试像这样使用map()
,但感到困惑:
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 })
}
我想看起来像这样:
{
0:{
formname1:'',
[ 0: {a:'', b:''},
1: {a:'', b:''},
]
},
1:{
formname2:'',
[ 0: {a:'', b:''},
1: {a:'', b:''},
]
},
.......
}
请大家帮忙
最佳答案
const finalData = {...this.state.data, formname: this.state.formname};
或
const finalData = {[this.state.formname]: this.state.data};
?
关于javascript - 将对象数组和字符串状态合并到新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58857507/