[英]how to assign variables to an object for submitting the Data using reactjs?
我的目標是在提交數據時將變量分配給新對象。
這是提交時出現的對象數組:
experience: [
{
Organisation: "",
ID: "",
From: "",
To: "",
Skills: []
},
{
Organisation: "",
ID: "",
From: "",
To: "",
Skills: []
}
]
但我希望對象應該是這樣的:
{
organisationName: "",
id: "",
from: "",
to: "",
skills: []
}
我已經這樣做了,但輸出沒有適當地出現在這個中。
handleSubmit = (e)=> {
e.preventDefault();
let obj = {
id: this.state.experience.map((item) => item.ID),
organisation: this.state.experience.map((item) => item.Organisation),
from: this.state.experience.map((item) => item.From),
to: this.state.experience.map((item) => item.To),
}
console.log("Object", obj)
}
任何人都可以幫我以正確的方式分配值嗎?
使用Object.fromEntries
映射條目並在鍵上調用toLowerCase
會更容易:
const lowercaseKeys = obj => Object.fromEntries(
Object.entries(obj)
.map(([key, val]) => [key.toLowerCase(), val])
);
const obj = this.state.experience.map(lowercaseKeys);
如果您還需要用另一個替換特定鍵,請使用.replace
:
const lowercaseKeys = obj => Object.fromEntries(
Object.entries(obj)
.map(([key, val]) => [
key.toLowerCase().replace('organisation', 'organisationName'),
val
])
);
const obj = this.state.experience.map(lowercaseKeys);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.