Destructuring Objects and Arrays in JavaScript
Pulling values out of objects and arrays into variables.
There are times when you need a few values from an object and end up writing
user.name, user.email and user.role over and over. Destructuring lets you
pull those values out into their own variables in one line.
Destructuring unpacks values from an object or array into separate variables.
Destructuring Objects
Put the property names you want inside curly braces on the left side of the =:
const user = { name: "Pam", email: "pam@dundermifflin.com", role: "Designer" }const { name, email } = userconsole.log(name) // "Pam"console.log(email) // "pam@dundermifflin.com"
The variable names have to match the property names. If you want a different name, rename it with a colon:
const { role: jobTitle } = userconsole.log(jobTitle) // "Designer"
Default Values
If a property might not exist, give it a default with =:
const { location = "Scranton" } = userconsole.log(location) // "Scranton"
The default is only used when the value is undefined.
Nested Objects
You can reach into nested objects too:
const order = {id: 42,customer: { name: "Jim", address: { city: "Scranton" } },}const {customer: {address: { city },},} = orderconsole.log(city) // "Scranton"
This gets hard to read quickly, so I usually stop at one level deep.
Destructuring Arrays
Arrays use square brackets, and values are matched by position instead of by name:
const colors = ["red", "green", "blue"]const [first, second] = colorsconsole.log(first) // "red"console.log(second) // "green"
Skip an item by leaving a blank spot, and collect the rest with ...:
const [, , third] = colors // "blue"const [head, ...rest] = colors// head: "red"// rest: ["green", "blue"]
A handy trick with array destructuring is swapping two variables without a temporary one:
let a = 1let b = 2;[a, b] = [b, a]// a: 2, b: 1
Destructuring Function Parameters
You can also destructure an object right in a function's parameters, which makes it clear which properties the function uses:
function greet({ name, role = "Employee" }) {return `Hi ${name}, ${role}`}greet(user) // "Hi Pam, Designer"
You'll see this all the time in React components, where props are destructured right in the function signature:
function Avatar({ src, alt, size = 40 }) {return <img src={src} alt={alt} width={size} height={size} />}
And if you've used React hooks, const [count, setCount] = useState(0) is just
array destructuring.
The syntax can look strange at first, but it makes your code a lot shorter and easier to read.
Have some feedback on this post? .