6

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.

Jigar Shah
  • 5,524
  • 2
  • 22
  • 37
  • you could use a white list for properties, or a black list. then iterate. – Nina Scholz Sep 04 '17 at 09:21
  • take a look at [this](https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object) – Max Sep 04 '17 at 09:26
  • Take a look at [One-liner to take some properties from object in ES6](https://stackoverflow.com/q/25553910/1048572) – Bergi Sep 04 '17 at 09:30

5 Answers5

6

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 }
Jonathan
  • 754
  • 4
  • 11
1

Drop the let (you're not declaring variables) and surround with parentheses:

({name: obj2.name, age: obj2.age} = obj1);
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
0

I guess you can use ES6 Object destructuring syntax

   var obj = { name: 'kailash', age: 25, des: 'backenddev'}
   ({name} = obj);
kailash yogeshwar
  • 716
  • 1
  • 7
  • 20
0

You could use the target object as template for the properties and assign the values of obj1 with a default value of the target object.

var obj1 = { name: 'Bob', age:  20, career: 'teacher' },
    obj2 = { name: '', age: '' };
    
Object.keys(obj2).forEach(k => obj2[k] = obj1[k] || obj2[k]);

console.log(obj2);
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
0

Another solution would be to write a reuable method for this. You can supply an object and the methods you would like to copy.

const duplicatePropertiesFromObject = (obj, propertyNames = [], newObj = {}) => {
  Object.keys(obj).forEach((key) => {
    if (propertyNames.includes(key)) {
      newObj[key] = obj[key];
    }
  });
  return newObj;
}
koningdavid
  • 7,141
  • 4
  • 31
  • 46