Consider this 'complex' object:
const obj = {
nestedArray: [
{ stuff: "things" }
],
nestedObj: {
key1: "value1",
key2: "value2"
}
}
I'm looking for an elegant one-line solution to destructure key1
, key2
, and stuff
from obj
.
My current solution looks like this and works just fine:
const { nestedArray, nestedObj: { key1, key2 } } = obj
const { stuff } = nestedArray[0]
But I would rather do it in one line like this:
const { array[0]: { stuff }, nestedObject: { key1, key2 } } = obj
But clearly that will not work. Any way of doing this in one line like I want? Or am I asking too much of ES6? I'd be more than happy to accept an answer of "no" as long is it provides a nice explanation as to why not.
You were very close, just use array destructuring with object destructuring to get stuff
:
const obj = {
nestedArray: [
{ stuff: "things" }
],
nestedObj: {
key1: "value1",
key2: "value2"
}
}
const { nestedArray: [{ stuff }], nestedObj: { key1, key2 } } = obj
console.log({ stuff, key1, key2 })