A Simple Guide to Objects In JavaScript - A brief overview

A Simple Guide to Objects In JavaScript - A brief overview

Hope you enjoy!

·

7 min read


Welcome guys! In today's blogpost we discuss Objects In Javascript & how to manipulate them to your will. Objects are very useful in Javascript as objects can store values, you can use objects to manipulate values and combine them into more complex objects. Follow along to get a better understanding of Objects & their implementation.

What is an Object?

Essentially an object is a data type that allows several variables together into one variable that contains keys and values. This is often used to represent or describe an entity. For example, a person, a user, a product, e.t.c.

Here is how you create an object

const user = {
id: 1,
firstName: Aman,
lastName: Velp,
age: 20
};

As visualized in this code snippet, an object is created by the use of curly brackets with instances inside it.

To read the property of an object you would use the object name with the variable name like follows

const user = {
id: 1,
firstName: Aman,
lastName: Velp,
age: 20
};

user.id // 1
user.firstName //Aman
user.age // 20
let user = 'Pranav'
id:1,

Updating property value

You can also update a property value using the same dot notation followed by an equal sign:

const user = {
    id: 1,
    firstName: "Sam",
    lastName: "Doe",
    age: 20
};

user.lastName = "Blue";
user.age = user.age + 1;
console.log(user); // {id: 1, firstName: "Sam", lastName: "Blue", age: 21}

Arrays of objects are the most common data type that you will encounter when working in web development, and that’s because most APIs (for example weather API, Twitter API, etc) return arrays of objects.

Let's say you’re querying the twitter API, here’s what a response could look like:

const tweets = [
    {
        id: 660837,
        message: "Hello Twitter",
        created_at: "2020-01-03 11:46:00",
        author: {
            id:6608,
            firstName: "Jad",
            lastName: "Jorban",
            handle: "JoubranJad"
            }
},   {
        id: 1080777336298195435,
        message: "How do you keep track of your notes?",
        created_at: "2021-02-19 15:32:00",
        author: {
            id: 109216891,
            firstName: "Sam",
            lastName: "Green",
            handle: "SamGreen"
        }
    }
];

This is an array of 2 objects, notice that the tweets variable is an array. A lot of developers confuse that because they see the objects inside the array and think that tweets is an object. Though, it’s an array of objects.

Knowing that tweets is an array, we can access properties on arrays (such as .length) and call array methods such as (.forEach(), .map(), etc)

Always visualize the inner object(s)

A very important tip when working with arrays of objects, when iterating over an array of objects, is to add console.log() throughout your code to visualize the object that you receive in the callback. Don’t rush it, take your time and visualize the array and then the objects inside.

Assuming the tweets array of objects from above, here’s how you iterate over it:

tweets.forEach(tweet => {
    console.log(tweet.author.handle)

You have to realize that tweet is an object. You will be able to visualize that in the console as you will see the object logged there.

Let’s say you’d like to log the handle of every user, then here’s how you can do that:

tweets.forEach(tweet => {
    console.log(tweet.author.handle);
});

Knowing that tweet is an object allows you to realize that you need to use the dot notation to access the author and then you do the same thing to access the handle.

Recap

  • Arrays of objects are the most common data type that you will encounter when working in web development, that's because most APIs (for example, a weather API, Twitter API, etc.) return arrays of objects.

  • A very important tip when working with arrays of objects, especially when iterating over an array of objects, is to add console.log() throughout your code to visualize the object that you receive in the callback.

Optional Chaining Recap

const getTotalSales = user => {
    const sum = 0;
    users.forEach(user = > {
        console.log(user.subscriber);
        sum += user.subscriber?.info?.value ?? 0
}
}

const users = [
    {id: 1, name: "Alex"},
    {id: 2, name : "Sam"},
    {id: 3, name: "Charlie", subscriber: {info: {value: 59}}}
    {id: 4, name : "Annand", subscriber: {info: {value: 32}}}    


]

In this case, optional chaining was used after the sum += operator. It was used because we were trying to access a property in the array user that all other objects didn’t have in common. All the objects have a common id: and name:, but not all objects have a common subscriber & info. Which is why optional chaining is needed to access those properties.

Transform arrays of objects

The .map() array method allows you to transform an array into another array of the same size. Here’s another example of .map() that we saw before:

const names = ["sam", "Alex"];

const upperNames = names.map(name => name.toUpperCase());
console.log(upperNames)

In this example, we transform an array of strings into a new array of strings where the items are uppercased.

The .map() works similarly for arrays of objects. You can transform an array of objects into a new array of objects, or, you can transform it into an array of strings or an array of numbers. This allows you to extract some properties from an array of objects. Here’s an example:

const tweets = [
    {
    id: 1080777336
    message: "Hello Twitter"
    created_at: "2020-01-03"
},
{
    id: 660837
    message: "How do you keep track of your notes?",
    created_at: "2021-02-19 15:32:00"
    }
];
const messages = tweets.map(tweet => tweet.message);
console.log(messages);//
["Hello Twitter", "How do you keep track of your notes?"]

Notice how we’re able to extract the message property from every single tweet so we ended up transforming an array of objects (tweets) into an array of strings (messages)

Don’t forget to console.log(tweet) inside the .map() callback to visualize the object.

Array of Objects II


If you are not that versed in JavaScript methods, this part may be a bit hard for you to understand.. but try to follow along!

All the examples in this lesson will use the following tweets variable:

const tweets = [
    {
        id: 10512,
        message: "Hello Twitter 👋",
        stats: {
            likes: 41,
            retweets: 54
        }
    },
    {
        id: 41241,
        message: "How do you keep track of your notes?",
        stats: {
            likes: 14,
            retweets: 20
        }
    }
];

Array.filter ()

tweets.filter(tweet => {
    console.log(tweet) //visualize the tweet
    return tweet.stats.likes > 30;
})

This code returns an array of tweets that have more than 30 likes. So, in our example, it will return an array of the first tweet.

We added a console.log(tweet) to visualize the tweet object because we’re working with an array of objects (tweets).

Once you get comfy with arrays of objects, you can rewrite it using arrow functions with implicit return.

tweets.filter (tweet => tweet.stats.likes > 30);

Array.find()

Calling the .find() method on an array of objects will return the first object that matches the condition you specify in callback, or undefined if no objects satisfy the condition.

const searchId = 41241; 
const tweet = tweets.find(tweet => tweet.id === searchId);
console.log(tweet);// {...} (2nd tweet object)

Array .some()

Calling the .some() method on an array object will return true when at least one item in the array satisfies the condition you specified in the callback. Otherwise, it returns false.

tweets.some(tweet => {
    console.log(tweet) //visualize the object
    return tweet.stats.likes > 30;
})

Can be written as

tweets.some(tweet => tweet.stats.likes > 30);
//true (at lesat one has more than 30 likes)
tweets.some(tweet => tweet.stats.likes > 30

Array .every()

Calling the .every() method on an array of objects will return true when every item in the array satisfies the condition you specified in the callback. Otherwise, it returns false

tweets.every(tweet => tweet.status.likes > 10); // true (all the tweets have more than 10 likes)
tweets.every(tweet => tweet.status.likes > 30); // false (some tweets don't have more than 30 likes)

Summary

  • Calling the .filter() method on an array of objects will return an array containing the objects that pass the condition you specify in the callback.

  • Calling the .find() method on an array of objects will return the first object that matches the condition you specify in the callback, or undefined if no objects satisfy the condition.

  • Calling the .some() method on an array of objects will return true when at least one item in the array satisfies the condition you specified in the callback. Otherwise, it returns false.

  • Calling the .every() method on an array of objects will return true when every item in the array satisfies the condition you specified in the callback. Otherwise, it returns false.

I hope this post helped you get a better understanding of how Objects, Array of Objects & Object manipulation works in javascript. Thanks for reading!

Did you find this article valuable?

Support Aman Velp by becoming a sponsor. Any amount is appreciated!