簡體   English   中英

如何將變量分配給使用reactjs提交數據的對象?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM