This post is a bit of a reboot from an earlier:
Destructuring β
Although this is not a standard English word, we could think π§ of it as dismantling or picking apart or as the opposite of structuring ποΈ something.
Objects
Some languages have structs. In JS, we have these glorious things known as objects. It's amazing and incredibly flexible that we can just spin up a couple of {}
and start adding πs and values. ππΎ
const person = {
fname: "Mark",
lname: "Galloway"
}
And to access our π, it's dot notation, .
: person.fname
. π
Back to Destructuring
If we need to access person.fname
a lot, we can do like this one: const { fname } = person;
.
Although when creating variables with const
we can normally make up our own names, in this case, the name inside of {}
must match the name of a property in person
- else it will be undefined
.
But, I Don't Like fname
Can't I Just Call It mickeyMouse
?
Yes - but just b/c you can, doesn't mean that you should!
Nevertheless, here we go:
const person = {
fname: "Mark",
lname: "Galloway"
}
const {fname: mickeyMouse} = person;
mickeyMouse; // "Mark" - π
So, we destructure a π by its name, then we can easily rename it to something else. This is especially handy when we retrieve JSON from a database that uses some other SQL naming conventions.
For example, we might get back something like: {"first_name": "Mark", "last_name": "Galloway"}
.
After parsing into JS, and assigning to a variable such as person
, we could do: const {first_name: fname} = person
.
Next time (assuming there's enough π on this post!) we'll see π examples of using this with function parameters.
Top comments (0)