I'd like to use ES6 destructuring to assign properties of an object, but can't figure out the syntax.
<= ES5:
var dst = {}; // already in existence, with its own props, methods, etc.
var src = { a: 'foo', b: 'bar', c: 'baz' };
dst.a = src.a;
dst.b = src.b;
>= ES6 (my own made-up, not-working syntax):
let dst = {};
let src = { a: 'foo', b: 'bar', c: 'baz' };
dst[{a, b}] = src;
Is it possible to use destructuring assignment onto an object? What's the correct syntax?
EDIT: In my use case, dst
is an object that existed well before needing to merge a subset of src
's properties; it is not a new Object created solely to 'borrow' from src
.
What is Destructuring? Destructuring is a characteristic of JavaScript, It is used to take out sections of data from an array or objects, We can assign them to new own variables created by the developer.
Destructuring is a JavaScript expression that allows us to extract data from arrays, objects, and maps and set them into new, distinct variables. Destructuring allows us to extract multiple properties, or items, from an array at a time.
Destructuring Assignment is a JavaScript expression that allows to unpack values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, nested objects and assigning to variables.
To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element. const [var1, var2, ...]
I think you’re going to have to repeat dst
:
({a: dst.a, b: dst.b} = src);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With