1

I'm trying to extract some values from an object and put them into an array. So far I have this:

let obj = {
  a: 'a',
  b: 'b',
  c: 'c',
  d: 'd',
  e: 'e'
};
    
let arr = [{a, b, c} = obj];
    
console.log(arr);

However, this is returning an array with just one object:

[ { a: 'a', b: 'b', c: 'c', d: 'd', e: 'e' } ]

My desired output would be:

['a', 'b', 'c']

Does anyone know what I'm doing wrong?

3
  • What exactly would you like as a result? {a, b, c} = obj just takes the first three values of your array and put them into three new variables, a, b and c. Commented Sep 25, 2018 at 21:05
  • What are you expecting your output to look like? ['a', 'b', 'c']? Commented Sep 25, 2018 at 21:06
  • yes thats correct @mhodges Commented Sep 25, 2018 at 21:07

3 Answers 3

2

You could take the values of a new object with short hand properties.

let obj = { a: 'a', b: 'b', c: 'c', d: 'd', e: 'e' },
    { a, b, c } = obj,
    arr = Object.values({ a, b, c });

console.log(arr);

Or take the wanted keys for a new array.

let obj = { a: 'a', b: 'b', c: 'c', d: 'd', e: 'e' },
    arr = ['a', 'b', 'c'].map(k => obj[k]);

console.log(arr);

Sign up to request clarification or add additional context in comments.

1 Comment

how about arr = [a,b,c]; over arr = Object.values({ a, b, c })
1

To achieve expected use below option
Use () around the assignment statement ,as {} is treated as block but not as object literal during destructuring assignment

let obj = {
  a: 'a',
  b: 'b',
  c: 'c',
  d: 'd',
  e: 'e'
};
//({a, b, c, ...rest} = obj) // to have access of rest of parameters
({a, b, c} = obj)
let arr = [a,b,c];

console.log(arr);

codepen - https://codepen.io/nagasai/pen/EeBBjQ?editors=1011

2 Comments

You really don't need the ...rest do you?
@MarkMeyer, it is not necessay but to have access of other parameters, i have used rest
0

You can do this inline by using the comma operator:

let obj = {
  a: 'a',
  b: 'b',
  c: 'c',
  d: 'd',
  e: 'e'
};
    
let arr = ({a, b, c} = obj, [a, b, c]);
    
console.log(arr);

2 Comments

This seems to create globals for a, b, and c. Wonder if that's avoidable?
It is if you first declare the variables and then evaluate the expression. Not as beautiful, but no globals.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.