Skip to content
Advertisement

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

I have the following object.

JavaScript

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

JavaScript

then i get in the user variable this output

JavaScript

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

JavaScript

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

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement