0

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?

  • Can you explain the actual criteria you're using for which properties you want to copy? – Barmar Sep 05 '19 at 00:47
  • This question is unclear: *"now I want to retrieve the `name` and `age` properties"*... so **you know** the properties you want, isn't that correct? – Gerardo Furtado Sep 05 '19 at 00:49
  • Does [Dynamically access object property](https://stackoverflow.com/questions/4244896/dynamically-access-object-property) help? – Barmar Sep 05 '19 at 00:49
  • You will always need to know which properties you want in the new object in order to both create the object and assign the values – gavgrif Sep 05 '19 at 00:49
  • Possible duplicate of [Is it possible to destructure onto an existing object? (Javascript ES6)](https://stackoverflow.com/questions/29620686/is-it-possible-to-destructure-onto-an-existing-object-javascript-es6) – Taki Sep 05 '19 at 00:57
  • `I have to know properties names such as "name" and "age" in advance` - yes, so? since you want to get `name` and `age`, so you already "know" the property names you want - I fail to see the issue – Jaromanda X Sep 05 '19 at 01:03
  • OP: Stack Overflow is a quite active community, so when asking a question please stick around for at least 5 minutes, to see the comments requiring clarification. Voted to close as *unclear*. – Gerardo Furtado Sep 05 '19 at 01:07
  • @Barmar I have updated my post to address my actual question –  Sep 05 '19 at 01:17
  • Are you sure you even need two different objects? Why not just `let student = person;`? Since the property names are the same, any function that expects a student will work with a person. – Barmar Sep 05 '19 at 01:39
  • @Barmar well, it works, but it also means that I have unwanted properties in my object, which can confuses other developers when they received this object, unwanted properties also take up extra memory usage –  Sep 05 '19 at 01:45
  • @Barmar so there is no a single statement solution? if there is no such a solution, I appreciate the fact. It just weird to me that such a successful language doesn't offer this useful feature –  Sep 05 '19 at 01:48
  • Sorry, no. Destructuring can be used to extract properties into variables. There's also object shorthand `{name, age}` that can create properties from variables. But there's no properties->properties shortcut. – Barmar Sep 05 '19 at 15:01
  • How can one object with 4 properties take up more memory than an object with 4 properties alongside another object with 2 properties? Is the person object going away when you create the student object? – Barmar Sep 05 '19 at 15:03
  • @Barmar that's why I feel strange, why javascript doesn't implement properties->properties shortcut. For another question you mentioned, according to what you suggest `let student = person;`, I have to include unwanted properties in the new object, those unwanted properties takes extra cost in memory, even though original object is destructed, becuase the new object should have cost less –  Sep 06 '19 at 00:10
  • When you do `student = person` it's not a new object, the two variables both refer to the *same* object. – Barmar Sep 06 '19 at 00:13
  • I guess the need for the properties->properties shortcut was not common enough or they couldn't come up with a good syntax for it. – Barmar Sep 06 '19 at 00:15
  • In most cases where you might want to do this, the right solution is an object-oriented approach, where you use classes and subclasses. – Barmar Sep 06 '19 at 00:16

3 Answers3

1

You could define a class, e.g.

class Student {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}

let student = new Student(person.name, person.age);

You might also consider making Person a class and then making Student a subclass of it, then you wouldn't need two different objects.

Barmar
  • 741,623
  • 53
  • 500
  • 612
-1

Create a function which takes object and array of properties to be extracted as arguments. Then create an empty object add the given properties to that object and return it.

const getProps = (obj, props) => 
     props.reduce((ac,a) => {
        ac[a] = obj[a];
        return ac;
     },{});

let person = {
   name: "Tom",
   age: "18",
   postcode: 1234,
   city: "Sydney"
}

console.log(getProps(person, ['name', 'age']))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
-1

I think this may help. Might not be the full answer, I do not fully understand what your asking to be honest.

You can access an object using a string like so

myObject[string]

Example ...

Let myFields = ["name", "age", "postcode"];

let myObject = {};

myFields.forEach(f => myObject[f] = "");

console.log(myObject);

// { name: "", age: "", postcode: "" }

Example 2 ...

let myObject = {};

myObject["name"] = "Daniel";
myObject["age"] = 32;
myObject["postcode"] = "78UH4";

console.log(myObject);

// { name: "", age: "", postcode: "" }

myObject.city = "Thurles";

console.log(myObject["city"])

// Thurles

How this helps with the struggle

Daniel

GaddMaster
  • 331
  • 3
  • 14