0

I have the following javascript code:

const {
  tr,
  selection: { $from }
} = state;

I understand that the above is a destructuring construct but I am unsure about the : { $from } part as there are no $from property in the selection object (see screenshot)...

There is no tr in state either...

Can someone please explain?

enter image description here

edit: Actually, there is indeed a $from property (see screenshot) but it is nested. Can someone please explain how desctructuring can fetch nested properties?

enter image description here

balteo
  • 23,602
  • 63
  • 219
  • 412
  • Do you get any value for `$from`? If you do, that suggests there *was* such a property. Maybe it's just missing later. Beware [Weird behavior with objects & console.log](https://stackoverflow.com/q/23429203) – VLAZ Apr 22 '21 at 07:38
  • @VLAZ Yes I indeed get a value for `$from`. Let me read the link you provided. :-) – balteo Apr 22 '21 at 07:40
  • "*Can someone please explain how desctructuring can fetch nested properties?*" it cannot. Not with the nesting shown in that screenshot because that's a completely different property that happens to share the same name. – VLAZ Apr 22 '21 at 07:51
  • The reason I did not find the `tr` property in `state` and the `$from` property in `state.selection` is because these were in the `__proto__` 's **getters**. – balteo Apr 28 '21 at 07:23

1 Answers1

1

Destructuring allows you unpack object fields into new variables.

For example, if your state object looks like this:

state = {
   selection: {
       ranges = [1,2,3],
       $head = "abc"
   },
   storedMarks = 99
}
const { selection, storedMarks } = state // destructuring

console.log(selection) // > { ranges:.., $head... } 
console.log(storedMarks) // > 99

New variables selection and storedMarks has been created.

If you are trying to retrieve tr and $from

const {
  tr,
  selection: {
     ranges: [
        $from: myFromValue
     ]
  }
} = state;

console.log(tr); // will print your tr value that is in `state` object, if it exists
console.log(myFromValue); // will print your $From value

terahertz
  • 2,915
  • 1
  • 21
  • 33