Let's say we have a Person
object as:
let person = {
name: "Tom",
age: "18",
postcode: 1234,
city: "Sydney"
}
Now I want to retrieve the name
and age
properties and assign them to a new object called student
as:
{ name: "Tom", age: "18" }
I can definitely manually create the student
object like so:
let student= {
name: person.name,
age: person.age
}
But the problem is I have to know properties names such as "name" and "age" in advance, so there is no intellisense support in an IDE like Visual Studio Code when I type properties' names
or
I can use rest operator as:
let { postcode, city, ...student} = person;
But this approach is not very straightforward because I still need to know how many properties in an object and for my case, student
object is a very simple object, but it will be error-prone if there is a dozen of properties in one object and I just want to retrieve one or two of them.
how can I do that in a most concise and efficient way?
Edited:
I actually meant that if there is an easy and advanced feature so I can get the job done in one statement as:
let student = { person.name, person.age }; // not valid syntax, I know
or
let student = { get person.name, get person.age }; // non existent syntax, but you get the idea
so I can rely on intellisense to define everything. It seems like I need to write at least two separate statements to achieve the goal, which doesn't sound right to me, I am new to JS, I can see that this feature could be very useful, how come it is not implemented to get it done in one statement?