Javascript 如何使用rest运算符从数组中自动获取属性名?

Javascript 如何使用rest运算符从数组中自动获取属性名?,javascript,Javascript,我有以下目标 let userInput = { "id": "22a52279-cc48-430e-ada6-88a3f67cbb8b", "first_name": "test", "email": "test@hotmail.com", "created_at": "2021-04-06T18:19:01.56

我有以下目标

let userInput = {
    "id": "22a52279-cc48-430e-ada6-88a3f67cbb8b",
    "first_name": "test",
    "email": "test@hotmail.com",
    "created_at": "2021-04-06T18:19:01.567Z",
    "salary": null,
    "department_name": null,
    "department_id": null,
    "last_name": null,
    "gender": null,
    "updated_at": "2021-04-06T18:19:01.567Z",
    "address": "ad12",
    "phone": null,
    "city": null,
    "university_name": null,
    "university_city": null,
    "about": null,
    "is_admin": null
}
如果我想从该对象获取一些属性并在另一个对象中使用它们,我将执行以下操作:

 const {first_name, address, phone, city, university_name, university_city, about} = this.userInput;
    this.user = {first_name, address, phone, city, university_name, university_city, about};
    console.log(this.user);
然后我在
user
变量中输入这个输出

{
    "first_name": "test",
    "address": "ad12",
    "phone": null,
    "city": null,
    "university_name": null,
    "university_city": null,
    "about": null
}
为了避免重复我的自我,我想将所有这些需要的proeprty名称存储在一个数组中并重用它,所以我尝试了

const getNeededProperties = ["first_name", " address", " phone", " city", " university_name", " university_city", " about"];
const {first_name, address, phone, city, university_name, university_city, about} = this.userInput;
this.user = {...getNeededProperties};

我将得到相同的输出-因此基本上我存储
名字
然后
地址
等等。。。作为局部变量 然后我将它们赋给用户对象-我对属性名进行了解构,它就开始工作了

但是当我试图从数组中删除属性名时

 const getNeededProperties = ["first_name", " address", " phone", " city", " university_name", " university_city", " about"];
      const {...getNeededProperties} = this.userInput;
      this.user = {...getNeededProperties};
我犯了一个错误

无法重新声明块作用域变量“getNeededProperties”

有什么方法可以让我自动控制所有这些吗?

您可以使用以下方法:

const userInput={
“id”:“22a52279-cc48-430e-ada6-88a3f67cbb8b”,
“名字”:“测试”,
“电子邮件”:test@hotmail.com",
“创建时间”:“2021-04-06T18:19:01.567Z”,
};
const neededProps=[“id”,“first_name”];
const user=neededProps.reduce((res,prop)=>({
…res[prop]:用户输入[prop]
}), {});

console.log(用户)您可以使用以下实用程序将字段从一个对象复制到另一个对象

const fieldsToCopy=[“名字”、“地址”、“电话”、“城市”、“大学名”、“大学城”、“关于”];
this.user=copyFields(this.userInput,fieldsToCopy);
copyFields.js

函数复制字段(原始对象、字段复制){
const newObject={};
用于(原始对象中的常量键){
if(字段复制.索引OF(键)!=-1){
newObject[key]=原始对象[key];
}
}
返回newObject;
}
const foo={
“名字”:“测试”,
“地址”:“ad12”,
“电话”:空,
“城市”:空,
“大学名称”:空,
“大学城”:空,
“关于”:空
}
const arr=[“名字”、“地址”、“电话”]
// 1
const user=arr.reduce((a,p)=>(a[p]=foo[p],a),{})
// 2
const user2=Object.fromEntries(arr.map((p)=>[p,foo[p]]))
console.log(用户)

console.log(user2)
似乎您的解构只是为了解构,为什么不创建一个
对象.getProperties([“first_name”])
函数并传递它呢?这也是我要建议的解决方案。然而,如果对象上存在给定的属性,我会额外检查reduce函数内部。我认为这取决于用例。通常,我喜欢在预期的情况下清楚地看到该属性的值为
undefined
,而不是根本看不到该属性all@blexTNX的答复