Reputation: 3186
Let's say i have these two Objects.
let object1 = {
a: 'value1',
b: 'value2',
c: 'value3',
d: 'value4',
e: 'value5'
}
let object2 = {
a: 'value6',
b: 'value7',
c: 'value8',
d: 'value9',
e: 'value10'
}
I want to assign values of c, d and e
properties of object2 to object1. Only these properties, not all, so object1 to be
let object1 = {
a: 'value1',
b: 'value2',
c: 'value8',
d: 'value9',
e: 'value10'
}
I know that i can do it this way
object1.c = object2.c;
object1.d = object2.d;
object1.e = object2.e;
but i want to know if there is a more elegant way with fewer lines of code. Some objects may have over 10 properties, and need to assing only 7-8 of them.
Thanks in advance!
Upvotes: 1
Views: 88
Reputation: 4451
You may use destructuring assignment and then Object.assign()
let object1 = { a: 'value1', b: 'value2', c: 'value3', d: 'value4', e: 'value5'};
let object2 = { a: 'value6', b: 'value7', c: 'value8', d: 'value9', e: 'value10'};
let {c, d, e} = object2;
Object.assign(object1, {c, d, e});
console.log(object1);
Upvotes: 3