Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructure object into an array

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];
like image 596
Stophface Avatar asked Oct 22 '19 16:10

Stophface


People also ask

How to destructure an array of objects with JavaScript?

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)

Is it possible to combine array destructuring and object destructuring?

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.

What is destructuring assignment in JavaScript?

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.

How do you destruct an array in C++?

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


Video Answer


2 Answers

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]);
like image 169
David Avatar answered Oct 10 '22 05:10

David


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));
like image 1
Nina Scholz Avatar answered Oct 10 '22 04:10

Nina Scholz