Destructure object into an array

Viewed 5447

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];
4 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]);

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));

There isnt a de-structure into array from an object.

But if you want all the keys / values of the object in an array format, you can use these:

let obj = {
    a: 'kitten',
    b: 'puppy',
    c: 'lion'
};

let keyArray = Object.keys(obj); 
// keyArray = ['a','b','c']
let valuesArray = Object.values(obj);
// valuesArray = ['kitten', 'puppy', 'lion'];

Do note that the order of the array is not guaranteed to follow the order of the object.

   Object.entries(obj).forEach( ([key, value]) => { 
   console.log(`${key}: ${value}`) 
  • Here, Object.entries () give array of key: value pair. You can use results as per your requirement.
Related