JavaScript object destructuring tips

I'm a full-stack developer from South Africa 🇿🇦. I love writing about JavaScript, HTML and CSS.
Search for a command to run...

I'm a full-stack developer from South Africa 🇿🇦. I love writing about JavaScript, HTML and CSS.
Happy to hear you enjoyed it 🙏
Hey Chris Bongers, I did not understand the dynamic name destructuring.
It basically is a way to use variables as the key selector.
In the example we might get getProperty from a function (like a select list)
So we can't do { name } as we don't know if it's name or age for instance. This way you can use a dynamic name (variable) to be the destructure selector.
Hope that makes a some sense?
Okay Chris Bongers. It's similar to Destructuring with a different name. We are storing the name with a different variable and using that variable to get another variable which will be used to get the value "Chris".
It took longer to understand. But, I hope my explanation makes sense :)
This is great, so happy to hear that 💖
Glad you enjoyed it 🙏
I really enjoyed the 'PLAY THIS ARTICLE' function but what would make it even better if it had a fixed position so I could pause without scrolling back to the top (and having to rush to find my place when I press play.) Very helpful article.
That's actually a hashnode feature, will tag Syed Fazle Rahman for reference. 💖
Thanks for tagging, Chris.
That's a great suggestion, Isabel Nava. We're already working on an upgrade to the listen feature. It'll be shipped soon.
Amazing Syed Fazle Rahman
Glad to hear you like the article 💖
Most of you know me for my consistency, a golden arrow in my blog series. I've written 1000 articles in 1008 days! Almost an article a day, and my honeymoon was the only holiday I ever took. I'm super proud of this achievement; it has been a fantasti...

It's not the first time I'll be talking about community. I think it's an essential aspect of any successful tool. This shows in my previous explorations of Astro, Medusa, and now Vendure as well. All these products thrive in a super open, welcoming, ...

The cool part about Vendure is how easy it is to set up and how abstract each layer is. Basically, we get the following elements: External database Server Worker Admin UI Frontend While this is amazing, it also brings a bit of complexity when it co...

The previous article looked at customizing Vendure on a data and process level. In this article, we'll look at customizing emails, as they are often a big part of a webshop system. We'll be looking at two different layers of customization for customi...

Even though Vendure is a pretty significant project out of the box, in some cases, we might want to go in and modify some elements to work to our specific use case. In this article, I'll take a high-level look at some elements we can customize within...

Regarding JavaScript, we get an extremely useful way of extracting properties from objects.
Note: Destructuring also works on arrays, but let's focus on objects for this one
Let's say we have a user object and want to extract the properties of individual variables.
const user = {
name: 'Chris',
age: 33,
};
Before ES2015, we would have to assign these variables by explicitly assigning them like so:
var name = user.name;
This still works in modern JavaScript. However, it can be optimized.
We can omit the double use binding of the name properties and destructure the properties like this.
const { name, age } = user;
console.log(name);
// Chris
console.log(age);
// 33
Wait, what? Pretty much magic, right? We don't have to double name the variables and can assign them directly to their variables.
Let's say you have an object with multiple fields. You want to extract one of the fields and keep track of whatever is left.
You might think we need to assign all the remaining properties, but this is built-in by using the spread operator.
const user = {
name: 'Chris',
age: 33,
username: 'DailyDevTips',
};
const { name, ...rest } = user;
console.log(name);
// Chris
console.log(rest);
// { age: 33, username: 'DailyDevTips' }
Quite often, your object will have multiple layers. With destructuring, we can also target nested properties.
const user = {
name: 'Chris',
age: 33,
username: 'DailyDevTips',
address: {
country: 'South Africa',
postalCode: '7700',
},
};
Let's take the above example. How can we extract the country in one go?
const {
address: { country },
} = user;
console.log(country);
// South Africa
But what happens if we want to extract the whole address object and the country?
In the above example, if we try to log address it will state: ReferenceError: address is not defined.
However we can simply pass another reference in the destructuring like this:
const {
address: { country },
address,
} = user;
console.log(address);
// { country: 'South Africa', postalCode: '7700' }
console.log(country);
// South Africa
Perhaps you want to destructure some properties under a different name.
Let's take the example above and state that we want to receive the address object named shippingAddress.
We can use the semicolon : divider to address a new name.
const { address: shippingAddress } = user;
console.log(shippingAddress);
// { country: 'South Africa', postalCode: '7700' }
This is a great way to create variables that you can directly use.
Let's retake our user object, we already destructured the age, but I forgot to mention this is an optional parameter.
Some users might have chosen not to set it. In that case, we can fall back on a default value.
Note: This is a bit weird for the age property, so see this as an example
const user = {
name: 'Chris',
age: 33,
};
const { age } = user;
console.log(age);
// 33
That works great, but let's see a user that doesn't have the age property.
const user = {
name: 'Yaatree',
};
const { age } = user;
console.log(age);
// undefined
We can destructure it with a value if we want to set a default age.
const { age = 25 } = user;
console.log(age);
// 25
All the above examples work based on flat objects, but a lot of the time, you'll have an array of users.
const users = [
{
name: 'Chris',
age: 33,
},
{
name: 'Yaatree',
age: 2,
},
];
We can loop over these items and destructure them inside the loop.
for (let { name, age } of users) {
console.log(`User: ${name} is ${age} years old 🎉`);
}
// 'User: Chris is 33 years old 🎉'
// 'User: Yaatree is 2 years old 🎉'
What happens when we only know the variable we want to destructure at runtime?
Let's say a user clicks a button that allows them to extract a random property from the object.
The handler would have the following property.
const getProperty = 'name'; // or 'age'
// How do we get this from the user now?
To use this, we can use the square bracket annotation.
const { [getProperty]: returnValue } = user;
console.log(returnValue);
// Chris
Let's say we have a function that returns an object.
const getProduct = () => {
return {
id: 1,
name: 'Macbook',
};
};
If we call it by default, it will look like this.
const product = getProduct();
console.log(product);
// { id: 1, name: 'Macbook' }
However, we only want the id from this function. Can we do that?
const { id } = getProduct();
console.log(id);
// 1
Yes, we can. We can simply destructure the return value and assign the property we need.
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter