1

I´m often using destructor to split an object into parts:

const foo = {
  a: "part 1",
  b: "part 2",
  c: "part 3",
}

//get a,b,c
const ({a,b,c}) = foo;

console.log(a,b,c) // "part 1, part 2, part 3"

I´m also sometimes using destructor to get parts of the objects that are properties:

const foo = {
  a: "part 1",
  b: "part 2",
  c: "part 3",
  d: {
    a: "part a from d",
    b: "part b from d",
    c: "part c from d",
  }
}

//just get a from d
const ({d: {a}}) = foo;  // I split out a here but not d

console.log(a) // "part a from d"
console.log(d) // d is not defined but I want d here

How can I get d here including a, b and c is it possible in the same line?

Dude
  • 1,045
  • 2
  • 15
  • 36

1 Answers1

2
  const { d, d: { a } = {} } = foo

Just destructure it twice. Or destructure two times:

const {d} = foo;
const {a} = d || {};
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Is it possible to do some kind of a safe navigation operation while destructing an object ? So maybe d is not existing but I am destructing a from it. I know there is a stage-1 safe navigation operator (?) but its not working here. – Dude Sep 10 '18 at 19:35
  • @dude there is, see edit :) – Jonas Wilms Sep 10 '18 at 19:59
  • never have seen this before. Thx – Dude Sep 10 '18 at 20:01