Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring nested objects as function parameters

In ES6 we can do:

let myFunc = ({name}) => {
  console.log(name)
}

myFunc({name:'fred'}) // => logs 'fred'

But how do I do it for nested properties like this:

myFunc({event:{target:{name:'fred'}}}) // => I want it to log 'fred'

What should myFunc look like so that it logs 'fred'?

I cannot change the object passed in. I wish to use destructuring to achieve this or some other suitable ES6 approach.

like image 337
danday74 Avatar asked Jun 12 '17 15:06

danday74


People also ask

Can we perform Destructuring on nested objects?

Gotchas of Nested DestructuringOne thing we cannot do with nested destructuring is to destructure a null or undefined value. If we attempt to do so it will throw an error: So, if we want to use nested destructuring we must be certain that the nested structure exists, or intentionally catch the thrown error.

What is nested Destructuring?

It's common for objects to contain nested objects and arrays. Destructuring allows us to extract properties that are nested in objects using the syntax that we learned above for destructuring arrays and objects.

How do you Destructure an array of objects?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.


1 Answers

You can simply do like this:

const myFunc = ({event: {target: {name}}}) => {
  console.log(name)
}

myFunc({event: {target: {name: 'fred'}}})
.as-console-wrapper { max-height: 100% !important; top: 0; }

Here is an other implementation, with both in parameters, but the second is entirely optionnal:

const myFunc = (
      {name: name},
      {event: {target: {name: eventTargetName = ''} = ''} = ''} = ''
    ) => {
      console.log(name, eventTargetName)
    }

myFunc({name:'fred'})
myFunc({name:'papi'}, {event: {target: {name: 'fredo'}}})
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 157
john Avatar answered Sep 30 '22 18:09

john