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
5 Answers
Reset to default 6Actually 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
版权声明:本文标题:javascript - how to destruct part of properties from an object - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744316581a2600294.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论