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)