我有这个数组
air_content: '',
compaction_method: 1,
concrete_cylinders: [
{
id: '',
specimen_name: 'A',
mould_number: '',
curing: 1,
age: 7
},
{
id: '',
specimen_name: 'A',
mould_number: '',
curing: 1,
age: 7
},
{
id: '',
specimen_name: 'A',
mould_number: '',
curing: 1,
age: 7
}
]当我发布数据时,我试图解析它们( formik将它们修改回文本,因此我需要将它们解析为后端的int )
我的文章看起来如下(除了嵌套的对象外,我希望它们也被解析为整数)。
axios.post('http://localhost:8123/samples/concrete', {
air_content: parseFloat(air_content),
compaction_method: parseInt(compaction_method),
concrete_cylinders
});下面是我所要做的代码的最佳尝试:
axios.post('http://localhost:8123/samples/concrete', {
air_content: parseFloat(air_content),
compaction_method: parseInt(compaction_method),
concrete_cylinders: {
[concrete_cylinders.id]: parseInt(concrete_cylinders.id),
[concrete_cylinders.curing]: parseInt(concrete_cylinders.curing)
}
});谢谢你的帮助
发布于 2019-03-28 01:01:32
在打电话给axios.post之前,你需要
concrete_cylinders.forEach(x => {
x.id = parseInt(x.id);
x.curing = parseInt(c.curing);
});或者,如果你真的想要的话,你可以像
axios.post('http://localhost:8123/samples/concrete', {
air_content: parseFloat(air_content),
compaction_method: parseInt(compaction_method),
concrete_cylinders: concrete_cylinders.map(x => {
x.id = parseInt(x.id);
x.curing = parseInt(c.curing);
return x;
});
});发布于 2019-03-28 01:11:23
下面是一个使用更新的扩展语法的版本
const concrete_cylinders = [
{
id: '',
specimen_name: 'A',
mould_number: '',
curing: '1',
age: '7'
},
{
id: '',
specimen_name: 'A',
mould_number: '',
curing: '1',
age: '7'
},
{
id: '',
specimen_name: 'A',
mould_number: '',
curing: '1',
age: '7'
}
]
const result = concrete_cylinders.map(o => ({
...o,
...{
curing: parseInt(o.curing),
age: parseInt(o.age)
}
}));
console.log(result);
发布于 2019-03-28 01:15:31
在发布之前,您可以尝试在数组上使用forEach。比如说..。
pojo = {
air_content: '',
compaction_method: 1,
concrete_cylinders: [
{
id: '3',
specimen_name: 'A',
mould_number: '',
curing: '1',
age: 7
},
{
id: '3',
specimen_name: 'A',
mould_number: '',
curing: '1',
age: 7
},
{
id: '3',
specimen_name: 'A',
mould_number: '',
curing: '1',
age: 7
}
]
}
pojo.concrete_cylinders.forEach(e => {
e.id = parseFloat(e.id)
e.curing = parseInt(e.curing)
//...anything else you want to change before posting
})然后将对象传递给您的axios.post
axios.post('http://localhost:8123/samples/concrete', pojo);我相信有一个方法可以用更少的行来完成,但是这应该可以解决你的问题。
https://stackoverflow.com/questions/55388616
复制相似问题