简体   繁体   English

如何将变量分配给使用reactjs提交数据的对象?

[英]how to assign variables to an object for submitting the Data using reactjs?

My objective is to assign the variables to new object while submitting the data.我的目标是在提交数据时将变量分配给新对象。

Here is the array of object as they appear while submitting:这是提交时出现的对象数组:

experience: [
    {
        Organisation: "",
        ID: "",
        From: "",
        To: "",
        Skills: []
    },
    {
        Organisation: "",
        ID: "",
        From: "",
        To: "",
        Skills: []
    }
]

But i want the object should be in this way:但我希望对象应该是这样的:

{
        organisationName: "",
        id: "",
        from: "",
        to: "",
        skills: []
    }

I have done in this way but output is not appearing in this appropriately.我已经这样做了,但输出没有适当地出现在这个中。

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)
}

Can anyone please help me to assign the values in a right way?任何人都可以帮我以正确的方式分配值吗?

It would be easier to use Object.fromEntries to map the entries and call toLowerCase on the keys:使用Object.fromEntries映射条目并在键上调用toLowerCase会更容易:

const lowercaseKeys = obj => Object.fromEntries(
  Object.entries(obj)
    .map(([key, val]) => [key.toLowerCase(), val])
);
const obj = this.state.experience.map(lowercaseKeys);

If you also need to replace a particular key with another, use .replace :如果您还需要用另一个替换特定键,请使用.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