react axios帖子以数组格式生成json。如何将其转换为“名称”:“值”类型格式

问题描述 投票:1回答:1

enter image description here

        const submitService = {
        serviceType: this.state.serviceType,
        dateOfService: this.state.dateOfService,
        vehicleId: this.state.vehicleId,            
        orderNum: this.state.orderNum,
        driverId: this.state.driverId,
        vendorName: this.state.vendorName,
        issueId: this.state.issueId
    };

    axios.post("http://localhost:8072/TruckyServiceMicroService/admin/services/saveService/", submitService)
        .then(response => {
            if (response.data != null) {
                this.setState(this.initialState);
                alert("Service Created Successfully");
            }

        });

这是构成json的const和使用const发送的发布请求。通过axios发送发布请求后,它会在json中添加方括号

    initialState = {
    serviceType: [], vehicleId: '', dateOfService: '', orderNum: '', driverId: '', vendorName: '', issueId: ''
}

这是状态

json reactjs post axios
1个回答
1
投票

如果您想快速修复,请更改:

const submitService = {
    serviceType: this.state.serviceType,
    dateOfService: this.state.dateOfService,
    vehicleId: this.state.vehicleId,            
    orderNum: this.state.orderNum,
    driverId: this.state.driverId,
    vendorName: this.state.vendorName,
    issueId: this.state.issueId
};

至:

const keys = ["serviceType","dateOfService","vehicleId","orderNum","driverId","vendorName","issueId"]
const submitService = Object.entries(this.state).reduce((res, ([key, val])) => {
    if(keys.includes(key))
      res[key] = Array.isArray(val)?val[0]:val
    return res
}, {})

这基本上会创建带有状态键和值对的有效负载,但是如果值是数组类型,它将仅使用它的第一个索引。

© www.soinside.com 2019 - 2024. All rights reserved.