最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Destructure object into an array - Stack Overflow

programmeradmin1浏览0评论

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
  • Are the keys always guaranteed to be ascending in lexical order? – byxor Commented Oct 22, 2019 at 16:16
  • 4 What about const array = Object.values(foo) or const 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:16
  • @byxor nope. They are not. – four-eyes Commented Oct 22, 2019 at 16:23
  • @SebastianSimon I was not aware of the Object.values() function. Thats just as good! – four-eyes Commented Oct 22, 2019 at 16:24
Add a comment  | 

4 Answers 4

Reset to default 14

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

   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.

发布评论

评论列表(0)

  1. 暂无评论