繁体   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