简体   繁体   中英

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.

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 }

放弃let (你没有声明变量)并用括号括起来

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM