Destructure object properties inside array for all elements

Me.Name picture Me.Name · Oct 16, 2016 · Viewed 12k times · Source

In its most basic form, having an array of objects:

let arr = [
  {val:"a"},
  {val:"b"}
];

How can destructuring be used, to obtain only the values ['a', 'b'].

getting the first value is easy:

let [{val:res}] = arr; //res contains 'a'

Obtaining all values inside the array can be done with the rest operator:

let [...res] = arr; //res contains all objects

Combining those, I expected to be able to use:

let [...{val:res}] = arr; //undefined, expected all 'val's (['a', 'b'])

The above returns undefined (Tested in FF). Some further testing seems to indicate that adding the rest operator when using an object destructuring as well doesn't use the iteration, but gets back the original object, e.g. let [...{length:res}] = arr; //res= 2. Some other trials, such as let [{val:...res}] = arr; or let [{val}:...res] = arr; produce syntax errors.

It's easy enough to do with other methods, such as using map on the array, but mostly I stumble upon this problem while destructuring multiple levels (an array with objects which have their own property containing an array). Therefore I'm really trying to get around how to do it solely with destructuring. For convenience: a test fiddle

edit

My apologies if I failed to explain the goal of the question. I'm not looking for a solution to a specific problem, only to find the correct syntax to use when destructuring.

Otherwise formulated, a first question would be: in the example above, why doesn't let [...{val:res}] = arr; return all values (['a', 'b']). The second question would be: what is the proper syntax to use a rest operator with a nested object destructuring? (pretty sure I've gotten some definitions mixed up here). It seems that the latter is not supported, but I haven't come across any documentation that (and why) it wouldn't be.

Answer

synthet1c picture synthet1c · Oct 16, 2016

You can destructure nested objects like this

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Nested_object_and_array_destructuring

let arr = [
  {val:"a"},
  {val:"b"}
];

const [{val: valueOfA}, {val: valueOfB}] = arr

console.log(
  valueOfA, valueOfB
)