I have the following object.
JavaScript
x
20
20
1
let userInput = {
2
"id": "22a52279-cc48-430e-ada6-88a3f67cbb8b",
3
"first_name": "test",
4
"email": "test@hotmail.com",
5
"created_at": "2021-04-06T18:19:01.567Z",
6
"salary": null,
7
"department_name": null,
8
"department_id": null,
9
"last_name": null,
10
"gender": null,
11
"updated_at": "2021-04-06T18:19:01.567Z",
12
"address": "ad12",
13
"phone": null,
14
"city": null,
15
"university_name": null,
16
"university_city": null,
17
"about": null,
18
"is_admin": null
19
}
20
if i want to get some properties from this object and use them in another object i will do:
JavaScript
1
4
1
const {first_name, address, phone, city, university_name, university_city, about} = this.userInput;
2
this.user = {first_name, address, phone, city, university_name, university_city, about};
3
console.log(this.user);
4
then i get in the user
variable this output
JavaScript
1
10
10
1
{
2
"first_name": "test",
3
"address": "ad12",
4
"phone": null,
5
"city": null,
6
"university_name": null,
7
"university_city": null,
8
"about": null
9
}
10
to prevent repeating my self – i wanted to store all this needed proeprty names in one array and reuse it so i tried
JavaScript
1
5
1
const getNeededProperties = ["first_name", " address", " phone", " city", " university_name", " university_city", " about"];
2
const {first_name, address, phone, city, university_name, university_city, about} = this.userInput;
3
this.user = {getNeededProperties};
4
5
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
1
4
1
const getNeededProperties = ["first_name", " address", " phone", " city", " university_name", " university_city", " about"];
2
const {getNeededProperties} = this.userInput;
3
this.user = {getNeededProperties};
4
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
1
13
13
1
const userInput = {
2
"id": "22a52279-cc48-430e-ada6-88a3f67cbb8b",
3
"first_name": "test",
4
"email": "test@hotmail.com",
5
"created_at": "2021-04-06T18:19:01.567Z",
6
};
7
const neededProps = ["id", "first_name"];
8
9
const user = neededProps.reduce((res, prop) => ({
10
res, [prop]: userInput[prop]
11
}), {});
12
13
console.log(user);