I have this object
const foo = {
a: 'kitten',
b: 'puppy',
c: 'lion'
};
Destructuring it into variables goes like this
const { a, b, c } = foo;
Is there a one-liner how to desctructre this into an array, so that the result ist
const array = [a, b, c];
How to destructure an array of objects with JavaScript? To destructure an array of objects with JavaScript, we can use the array destructuring syntax. const someArray = [ { data: 1 }, { data: 2 }, { data: 3 }] const [ { data: array0 }, { data: array1 }, { data: array2 } ] = someArray console.log (array0, array1, array2)
Array and Object destructuring can be combined. Say you want the third element in the array props below, and then you want the name property in the object, you can do the following: When deconstructing an object, if a property is not accessed in itself, it will continue to look up along the prototype chain.
The destructuring assignment is a cool feature that came along with ES6. Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. That is, we can extract data from arrays and objects and assign them to variables.
Array destructuring 1 Basic variable assignment 2 Assignment separate from declaration. ... 3 Default values. ... 4 Swapping variables. ... 5 Parsing an array returned from a function. ... 6 Ignoring some returned values 7 Assigning the rest of an array to a variable 8 Unpacking values from a regular expression match. ...
There's no "one-liner" I know of that uses destructuring.
You can use one of these instead (which don't use destructuring):
(1)
const array = [foo.a, foo.b, foo.c]
(2, as pointed out by @Sebastian Simon)
const array = Object.values(foo);
(3, as pointed out by @Sebastian Simon)
const array = ['a', 'b', 'c'].map(k => foo[k]);
You could take a function, destructure the wanted properties and return an array with the wanted order.
const
getABC = ({ a, b, c }) => [a, b, c],
foo = { a: 'kitten', b: 'puppy', c: 'lion' };
console.log(getABC(foo));
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