Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to destruct part of properties from an object

For example, I got an object like this:

obj1 = {
     name: 'Bob',
     age:  20,
     career: 'teacher'
  }

Now I need to duplicate part of its properties instead all of them.

obj2 = {
     name: '',
     age: '',
  }

I know I can do it like obj2.name = obj1.name, which will be verbose if many properties need to be duplicated. Are there any other quick ways to solve this problem? I tried

let {name: obj2.name, age: obj2.age} = obj1;

but got error.

like image 664
xiaojie Luo Avatar asked Sep 04 '17 09:09

xiaojie Luo


1 Answers

Actually you don't need object destructuring, just simple assignment:

obj2 = { name: obj1.name, age: obj1.age }

Now, obj2 holds wanted properties:

console.log(obj2);
// Prints {name: "Bob", age: 20}

If you want to merge old properties of obj2 with new ones, you could do:

obj2 = { ...obj2, name: obj1.name, age: obj1.age }
like image 193
Jonathan Avatar answered Oct 13 '22 02:10

Jonathan