我有这个数组
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)
}
});
谢谢您的帮助
答案 0 :(得分:3)
在致电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;
});
});
答案 1 :(得分:2)
以下是使用较新的spread syntax的版本:
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);
答案 2 :(得分:1)
您始终可以在发布前尝试在阵列上使用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);
我敢肯定有一种方法可以减少行数,但这应该可以解决您的问题。