Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object property assignment with destructuring?

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.

like image 525
ericsoco Avatar asked Nov 16 '15 19:11

ericsoco


People also ask

What is Destructuring props assignment?

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.

How do you Destructure an object?

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.

What are Destructuring assignments?

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.

How do you Destructure a property in JavaScript?

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, ...]


1 Answers

I think you’re going to have to repeat dst:

({a: dst.a, b: dst.b} = src);
like image 82
Ry- Avatar answered Oct 18 '22 12:10

Ry-