Skip to content
Advertisement

How can i get automatically property names from array with rest operator?

I have the following object.

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
}

if i want to get some properties from this object and use them in another object i will do:

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

then i get in the user variable this output

{
    "first_name": "test",
    "address": "ad12",
    "phone": null,
    "city": null,
    "university_name": null,
    "university_city": null,
    "about": null
}

to prevent repeating my self – i wanted to store all this needed proeprty names in one array and reuse it so i tried

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

i will get the same output – so basically i store first_name then address etc… as local variables and then i am assaigning them to the user object – i destructure the property names and it is working

but when i try to rest the property names from the array

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

i get error

Cannot redeclare block-scoped variable ‘getNeededProperties’.

Is there some way that i con all of this automatically ?

Advertisement

Answer

You can use reduce for this:

const userInput = {
    "id": "22a52279-cc48-430e-ada6-88a3f67cbb8b",
    "first_name": "test",
    "email": "test@hotmail.com",
    "created_at": "2021-04-06T18:19:01.567Z",
};
const neededProps = ["id", "first_name"];

const user = neededProps.reduce((res, prop) => ({
    ...res, [prop]: userInput[prop]
  }), {});
  
console.log(user);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement