Is there a way to clone an object with specified keys. For example you have this object
const User = {
firstName: '',
lastName: '',
age: '',
gender: '',
job: '',
}
and you just want to clone or extract the firstName
and lastName
to create another object like:
const UserPublicInfo = {
firstName,
lastName,
}
I know a few solutions but...
Solution #1: Manual
const UserPublicInfo = {
firstName: User.firstName,
lastName: User.lastName,
}
Caveat
There is no problem with a small list but this is going to be tedious with a large list, let's say 10+ keys or more.
Solution #2: Rest Operator
We can omit the keys specifically with Rest Operator
const { firstName, lastName, ...UserPublicInfo } = User
Caveat
This is easier than the first solution but the problem is what if you don't know the properties of the User
object? Yes you can console.log
the content but what if later in your development a team mate has updated this User
object and decided to add another property, your app will mostly like cause errors along the way. So security-wise Solution #1
is better.
I was hoping it could be done easy like in the following code but it throws error on my transpiler.
const UserPublicInfo = { firstName, lastName } = User
Are there better solutions out there for this use-case?