DEV Community

Cover image for Working With Complex Objects in Javascript - The Friendly Beginner’s Guide
Sarit Chaet Hudis
Sarit Chaet Hudis

Posted on • Updated on

Working With Complex Objects in Javascript - The Friendly Beginner’s Guide

When I first started working with more and more complex objects in JavaScript (such as API data), I noticed something that makes me work considerably slower. I did not take the time to understand the structure of the object and the data inside it.

I study in a full-stack bootcamp, so I saw this happen to a lot of us, especially beginner coders:
We love to jump right in and try out stuff, write and see what happens. This is fun! And can be a good approach sometimes.
But in the case of complex objects and newbie coders.. not so much.

If you have the same problem, hopefully this will help you.

Making sense of our object

Before going through the object itself, make sure you are familiar with the difference between values and references in JavaScript (if this is new to you, here's a good place to catch up.

This is because many times we want to get a nested object or array and change a part of it, and we need to feel confident when we ask ourselves: "Did I just change the actual object in my data? Or did I just change a copy I created?"

Now. How do I approach a new complex object?
Let's say we want to look at data of an online store selling NFTs.
Here's our object:

const NFTStore = {
  artPieces: [
    {
      pieceName: "Emo Flamingos",
      price: 30,
      ownerList: [
        {
          name: "Fida Ernest",
          userID: 23849,
          purchaseDate: "09/13/2021",
        },
        {
          name: "Eric Karger",
          userID: 23510,
          purchaseDate: "09/13/2021",
        },
      ],
    },
    {
      pieceName: "Where is my bit wallet",
      price: 100,
      ownerList: [],
    },
  ],
  storeCredits: 1000,
};
Enter fullscreen mode Exit fullscreen mode

let's say we want to add a new buyer to the owners list of a piece that was just purchased.
How will we approach this?
This is the place to take the time and Read the Object.
Try and extract its structure, even in a small comment in your code, for example:

// NFTStore {...}
// artPieces [piece1, piece2..]
//      piece1 {pieceName, price, ownerList}
//          ownerList [ owner1, owner2..]
//              owner {name, userID, purchaseDate}
// storeCredits (number)
Enter fullscreen mode Exit fullscreen mode

This is easier said than done, I know, but I guarantee every minute you put into this will save you at least 10 times when writing code.
And who doesn't want to be a 10X programmer, right? 😜

Reaching Inside, but Knowingly

Now that we are familiar with our data object, we can reach inside it better.
Let's for example get the price of the first piece in our store, the famous "Emo Flamingo"🦩.

We'll do it hard-coded for now.
We need to get into our NFTStore, and inside the first piece.
let's look back at the structure we saw, and see that the pieces are inside an array that's inside the store object.
This means we can start with:

const EmoFlamingoPrice = NFTStore.artPieces[0].price;
Enter fullscreen mode Exit fullscreen mode

the first dot is because artPieces is a key inside the NFTStore object.
the array index is because artPieces' value is .. an array. and the 0 is just for now.
and the last dot is because price is the key we want inside the object "artPieces[0]".
console logging that will give you the price value:

console.log(EmoFlamingoPrice); //30
Enter fullscreen mode Exit fullscreen mode

Great job for following through!
Now We can take it a step or two further.

Changing an object's content

Let's say we have a new buyer for this piece.

const buyer = {
  name: "Rose Daniel",
  userID: 23849,
  purchaseDate: "11/29/2021",
};
Enter fullscreen mode Exit fullscreen mode

To add her as the new buyer, we need to push the buyer object to the owners array, and add the piece's price to the NFTStore credits.
The owner array of the piece we want is available here:

NFTStore.artPieces[0].ownerList
Enter fullscreen mode Exit fullscreen mode

so we can simply push the new buyer:

NFTStore.artPieces[0].ownerList.push(buyer);
//see the list with new buyer :
console.log(NFTStore.artPieces[0].ownerList); 
Enter fullscreen mode Exit fullscreen mode

Great! Now we only need to get the piece's price and add it to the NFTStore credits. We already know the price, so let's focus on reaching the store's credits.
Look back on the structure and try to see how to do that.
.
.
.
.
Easy- it's just a key inside the NFTStore object!

NFTStore.storeCredits += NFTStore.artPieces[0].price;
console.log(NFTStore.storeCredits); //new credit is 1030
Enter fullscreen mode Exit fullscreen mode

Refactoring

Now we can generalize and write a function that gets a buyer and a piece name, and adds the buyer to the owner's list, as well as its price to the store credits.
See if all is clear, and if not, write me a comment and I'll clarify 😁

function buyPiece(NFTStore, buyer, pieceName) {
  // get the piece using its name
  const piece = NFTStore.artPieces.find(
    (piece) => piece.pieceName === pieceName
  );
  // add buyer to owner list
  piece.ownerList.push(buyer);
  // add piece price to store credit
  NFTStore.storeCredits += piece.price;
}
Enter fullscreen mode Exit fullscreen mode

The '.find' Method

The '.find' method receives a callback function that tells it how to find its target. 'find' iterates over the array, in this case the art pieces, and for each (piece) it checks whether the current piece name equals the name that the function buyPiece was given.
"find" returns the first result that passes the callback function test, so it's meant for unique values such as IDs - I used the piece's name instead but notice it might not be unique! So in reality you should use '.find' to search using an ID .

That's it folks, hope I helped to clarify this somewhat confusing topic for you.

I'm more than happy to receive comments, suggestions, and anything else in the comments!

Discussion (4)

Collapse
rbuchmeier profile image
Ryan Buchmeier

This is a great starter! However I could find a beginner getting caught by mutability. Probably worth mentioning that if they assign any variable/property/etc... to an object, that is a reference and not a clone.

Collapse
saritchaethudis profile image
Sarit Chaet Hudis Author

Thanks Ryan! I totally agree , that's why I added a link to a really nice article about value vs. reference. It is really critical to grasp that when working with (not only reading) objects.

Collapse
rbuchmeier profile image
Ryan Buchmeier

Didn't catch that. Nice job!

Collapse
mugammad profile image
Mugammad

Very good explanation thank you.