What is destructuring assignment ?
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
- From MDN
Advantages
Makes code concise and more readable.
We can easily avoid repeated destructing expression.
Some use cases
To get values in variable from Objects, array
let obj = { 'a': 1,'b': {'b1': '1.1'}} let {a,b,b:{b1}} = obj console.log('a--> ' + a, '\nb--> ', b, '\nb1---> ', b1) let obj2 = { foo: 'foo' }; let { foo: newVarName } = obj2; console.log(newVarName); let arr = [1, 2, 3, 4, 5] let [first, second, ...rest] = arr console.log(first, '\n', second, '\n', rest) // Nested extraction is possible too: let obj3 = { foo: { bar: 'bar' } }; let { foo: { bar } } = obj3; console.log(bar);To change only desired property in an object
let arr = [{a:1, b:2, c:3},{a:4, b:5, c:6},{a:7, b:8, c:9}] let op = arr.map( ( {a,...rest}, index) => ({...rest,a:index+10})) console.log(op)To extract values from parameters into standalone variables
// Object destructuring: const fn = ({ prop }) => { console.log(prop); }; fn({ prop: 'foo' }); console.log('------------------'); // Array destructuring: const fn2 = ([item1, item2]) => { console.log(item1); console.log(item2); }; fn2(['bar', 'baz']); console.log('------------------'); // Assigning default values to destructured properties: const fn3 = ({ foo="defaultFooVal", bar }) => { console.log(foo, bar); }; fn3({ bar: 'bar' });To get dynamic keys value from object
let obj = {a:1,b:2,c:3} let key = 'c' let {[key]:value} = obj console.log(value)To swap values
const b = [1, 2, 3, 4]; [b[0], b[2]] = [b[2], b[0]]; // swap index 0 and 2 console.log(b);To get a subset of an object
subset of an object:
const obj = {a:1, b:2, c:3}, subset = (({a, c}) => ({a, c}))(obj); // credit to Ivan N for this function console.log(subset);To get a subset of an object using comma operator and destructuring:
const object = { a: 5, b: 6, c: 7 }; const picked = ({a,c}=object, {a,c}) console.log(picked); // { a: 5, c: 7 }
To do array to object conversion:
const arr = ["2019", "09", "02"], date = (([year, day, month]) => ({year, month, day}))(arr); console.log(date);To set default values in function. (Read this answer for more info )
function someName(element, input, settings={i:"#1d252c", i2:"#fff", ...input}){ console.log(settings.i); console.log(settings.i2); } someName('hello', {i: '#123'}); someName('hello', {i2: '#123'});To get properties such as
lengthfrom an array, function name, number of arguments etc.let arr = [1,2,3,4,5]; let {length} = arr; console.log(length); let func = function dummyFunc(a,b,c) { return 'A B and C'; } let {name, length:funcLen} = func; console.log(name, funcLen);
What is destructuring assignment ?
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
- From MDN
Advantages
Makes code concise and more readable.
We can easily avoid repeated destructing expression.
Some use cases
To get values in variable from Objects, array
let obj = { 'a': 1,'b': {'b1': '1.1'}} let {a,b,b:{b1}} = obj console.log('a--> ' + a, '\nb--> ', b, '\nb1---> ', b1) let obj2 = { foo: 'foo' }; let { foo: newVarName } = obj2; console.log(newVarName); let arr = [1, 2, 3, 4, 5] let [first, second, ...rest] = arr console.log(first, '\n', second, '\n', rest) // Nested extraction is possible too: let obj3 = { foo: { bar: 'bar' } }; let { foo: { bar } } = obj3; console.log(bar);To change only desired property in an object
let arr = [{a:1, b:2, c:3},{a:4, b:5, c:6},{a:7, b:8, c:9}] let op = arr.map( ( {a,...rest}, index) => ({...rest,a:index+10})) console.log(op)To extract values from parameters into standalone variables
// Object destructuring: const fn = ({ prop }) => { console.log(prop); }; fn({ prop: 'foo' }); console.log('------------------'); // Array destructuring: const fn2 = ([item1, item2]) => { console.log(item1); console.log(item2); }; fn2(['bar', 'baz']); console.log('------------------'); // Assigning default values to destructured properties: const fn3 = ({ foo="defaultFooVal", bar }) => { console.log(foo, bar); }; fn3({ bar: 'bar' });To get dynamic keys value from object
let obj = {a:1,b:2,c:3} let key = 'c' let {[key]:value} = obj console.log(value)To swap values
const b = [1, 2, 3, 4]; [b[0], b[2]] = [b[2], b[0]]; // swap index 0 and 2 console.log(b);To get a subset of an object
subset of an object:
const obj = {a:1, b:2, c:3}, subset = (({a, c}) => ({a, c}))(obj); // credit to Ivan N for this function console.log(subset);To get a subset of an object using comma operator and destructuring:
const object = { a: 5, b: 6, c: 7 }; const picked = ({a,c}=object, {a,c}) console.log(picked); // { a: 5, c: 7 }
To do array to object conversion:
const arr = ["2019", "09", "02"], date = (([year, day, month]) => ({year, month, day}))(arr); console.log(date);To set default values in function. (Read this answer for more info )
function someName(element, input, settings={i:"#1d252c", i2:"#fff", ...input}){ console.log(settings.i); console.log(settings.i2); } someName('hello', {i: '#123'}); someName('hello', {i2: '#123'});To get properties such as
lengthfrom an array, function name, number of arguments etc.let arr = [1,2,3,4,5]; let {length} = arr; console.log(length); let func = function dummyFunc(a,b,c) { return 'A B and C'; } let {name, length:funcLen} = func; console.log(name, funcLen);
It is something like what you have can be extracted with the same variable name
The destructuring assignment is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables. Let's get the month values from an array using destructuring assignment
var [one, two, three] = ['orange', 'mango', 'banana'];
console.log(one); // "orange"
console.log(two); // "mango"
console.log(three); // "banana"
and you can get user properties of an object using destructuring assignment,
var {name, age} = {name: 'John', age: 32};
console.log(name); // John
console.log(age); // 32
It seems impossible, because, while looking the same, the destructuring assignment and object syntaxes are completely different things.
let a, b;
{a,b} = x <-- {a,b} is not an object
If you try returning the result of destructuring assignment, it will still be returning x, the full object.
const result = {a,b} = x
// `result` is the full object
or
const result = ({a,b} = x);
// `result` is the full object
Anyway, writing such one-liners could be extremely confusing to teammates. It would raise my eyebrows during a peer review anyways :)
I think what you need is to filter the object by key without middle variables.
Here is my solutions:
let x = {a:1,b:2,c:3}
let y = {}
;({a: y.a, b: y.b} = x)
let filterObjectByKeys = (object, keys) => Object.fromEntries(keys.map(k => [k, object[k]]))
let x = {a:1,b:2,c:3}
let y = filterObjectByKeys(x, ['a', 'b'])
Reference:
- Assign value to new object via destructuring
- Filter object properties by key in ES6