Reputation: 725
Lets assume we have such function:
const func = (a, b, {c: {d}}) => {console.dir(c)}
How is this function should be called and what structure of 3rd parameter?
I tried a lot of variations, but always got an error: Cannot destructure property
dof 'undefined' or 'null'.
Thanks!
Upvotes: 1
Views: 3393
Reputation: 1724
const func = (a, b, {c: {d}}) => {console.dir(d)}
func(null, null, {c: {d: document.location}});
This function has to be called with object that has key c
, which has object with key d
as value:
func(a, b, {c: {d: document.location }})
console.dir()
takes any JS object as parameter.
{ c: {d}}
is a syntax called object destructuring and its purpose in this context is unpacking fields from objects passed as function parameter.
{d}
is shorter syntax for object with key d
and value of variable d
({d: d}
).
To unpack variable d
from object under key c
, that object have to have that key initialized! But when you further destructurize the object passed as argument, you don't have that object as a variable in the scope.
In example you have provided, you will not be able to access object c
, as it has been destructurized and only object d
is available. Either you have mistake in your code or you need something like Anurat Chapanond has posted.
Upvotes: 1
Reputation: 2987
Here is one example.
const func = (a, b, {c: {d}}) => {console.dir(c)},
c = { d: 'hello' }
func(1, 2, { c })
I define c as an object with a property d which is a string 'hello'.
when func is called, the third parameter I pass to the function is an object with a property c.
{ c } is a shorthand for { c: c }
Upvotes: 0