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];
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];
Share
Improve this question
asked Oct 22, 2019 at 16:15
four-eyesfour-eyes
12.4k36 gold badges129 silver badges252 bronze badges
4
|
4 Answers
Reset to default 14There'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));
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.
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.
const array = Object.values(foo)
orconst array = ["a", "b", "c"].map((key) => foo[key])
? I’m not aware of a one-liner using destructuring. – Sebastian Simon Commented Oct 22, 2019 at 16:16Object.values()
function. Thats just as good! – four-eyes Commented Oct 22, 2019 at 16:24