10

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];
four-eyes
  • 10,740
  • 29
  • 111
  • 220

4 Answers4

13

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]);
David
  • 3,552
  • 1
  • 13
  • 24
2

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));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1
   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.
Developer
  • 3,309
  • 2
  • 19
  • 23
0

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.

Isaac Khoo
  • 525
  • 3
  • 9