![](/img/trans.png)
[英]how to pass json body as String in FETCH PUT API in react js
[英]React JS - Modify body JSON in HTTP fetch
我需要在下面的方法中修改“modelList”:
fetch(fetchAddress, {
method: 'POST',
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: JSON.stringify(this.props.modelList)
})
'modelList' 生成以下 JSON:
{list:[{"property1":"...","property2":"...","property3":"...","property4":"..."},{"property1":"...","property2":"...","property3":"...","property4":"..."}]}
但我需要將其發送到 API 代替:
[{"property2":"...","property3":"..."},{"property2":"...","property3":"..."}]
修改數組或 JSON 的最佳方法是什么,以便我可以發送 API 期望的內容?
我猜 OP 想從每個 object 中刪除第一個屬性。
您可以使用Object.entries
和解構賦值,然后返回一個新的 object 和Object.fromEntires
:
請注意,
Object.fromEntries
是“相當”新的,因此您可以使用簡單的減速器。
// {list:[{"property1":"...","property2":"...","property3":"...","property4":"..."},{"property1":"...","property2":"...","property3":"...","property4":"..."}]} const modeList = { list: [ { property1: 1, property2: 2, property3: 3, property4: 4 }, { property1: 1, property2: 2, property3: 3, property4: 4 } ] }; const modified = modeList.list.map(obj => { const [, ...rest] = Object.entries(obj); return Object.fromEntries(rest); }); // [{"property2":"...","property3":"..."},{"property2":"...","property3":"..."}] console.log(modified);
我最終使用這條線來實現我想要的:
const modifiedModelList = this.state.modelList.map(({property1, property4, ...item}) => item)
這從數組中刪除了 property1 和 property4,我現在可以使用 modifedModelList 傳遞給 API 方法。
抱歉 - 這可能更像是一個 JS 問題,而不是 ReactJS 問題。
In my opinion, create an object parser that takes the js model object as a parameter, then return the object that the API expects with no unused or vulnerable properties:
這是一個例子:
// lets take an object holiday for example
const holidayDataContract = (model) => {
return {
Id: model.id,
Title: model.title,
Notes: model.note,
Date: model.date,
}
}
// you can then use the above function to get the object that the API expects
const myFormObjects = [{...},{...}]
const objectToSend = myFormObjects.map(k=> holidayDataContract(k))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.