admin管理员组

文章数量:1405170

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.

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.

Share Improve this question edited Sep 4, 2017 at 9:21 Jigar Shah 6,2232 gold badges31 silver badges41 bronze badges asked Sep 4, 2017 at 9:19 xiaojie Luoxiaojie Luo 8710 bronze badges 3
  • you could use a white list for properties, or a black list. then iterate. – Nina Scholz Commented Sep 4, 2017 at 9:21
  • take a look at this – Max Commented Sep 4, 2017 at 9:26
  • Take a look at One-liner to take some properties from object in ES6 – Bergi Commented Sep 4, 2017 at 9:30
Add a ment  | 

5 Answers 5

Reset to default 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 }

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

({name: obj2.name, age: obj2.age} = obj1);

I guess you can use ES6 Object destructuring syntax

   var obj = { name: 'kailash', age: 25, des: 'backenddev'}
   ({name} = obj);

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);

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;
}

本文标签: javascripthow to destruct part of properties from an objectStack Overflow