Javascript, Learning Programming

How to Remove a Property from an Array of Objects

A lot has happened in the past month which I will save for my next post and in the process I have decided if the internet speed is good enough I will be a member of the Echo Platoon of Code Platoon‘s coding boot camp. I have gone back and forth in trying to decide if a boot camp is a good thing or not, but at this point, I am just going to do it and hopefully get a decent paying job at the end. When the boot camp finishes it will be one month before I am an EXPERT at being unemployed. Just in case you’re curious being an expert is the same thing as 10 years of full-time study. There you have it!

The boot camp begins in January and before I can actually participate I must go through Flatiron’s online boot camp prep which covers some javascript and ruby on rails. I got stuck for three days on the Online Shopping Cart Lab for a very STUPID reason, and before I forget how I fixed the problem I decided to write it down. There’s nothing like writing about it to help cement it in the brain.

The Problem Statement

You are given a cart variable that points to an empty array. The removeFromCart() function accepts one argument, the name of the item that should be removed.

  • If the cart does not contain a matching item, the function should print out That item is not in your cart. and return the unchanged cart.
  • If the item is present in the cart, the function should remove the object from the cart and then return the updated cart.

The Analysis

This didn’t seem like it would be difficult – but THREE days later I was ready to pull my hair out! This is a simple if/else statement with a for loop to iterate through the object – ahem, array of objects.

I wrote the code and tested in chrome’s console and in codepen AND it worked in both places, but when I put it in the learn IDE it didn’t work! After a few days of banging my head up against the wall, I finally asked for some help. What I discovered was I set up my test object incorrectly. Doh!

My Incorrect Setup

The test object:

var cart = {
"watermelon": "$72",
"milk": "$2",
"candy": "$82",
"wine": "$7",
"fruit": "$29"
};
function removeFromCart(item) {
// write your code here
if ( cart.hasOwnProperty(item) === false ) {
console.log( "That item is not in your cart." );
return cart;
} else {
for ( var key in cart ) {
if ( item === key ) {
cart.slice(0, 1);
return cart;
}
}
}
}
removeFromCart("wine");

What happened was in the Chrome console and Codepen wine was removed from the cart, but in the Learn IDE it was not.

The Correct Code & Explanation of How it Works

First of all, I set up the cart as one object instead of an array of objects. Remember this for the future: Objects have properties. A list of grocery store items are all similar and each item with its price is one item in a list. The cart itself has these two properties: item and itemPrice.

Cart Object


var cart = {
["watermelon": "$72"],
["milk": "$2"],
["candy": "$82"],
["wine": "$7"],
["fruit": "$29"]
};

BIG DIFFERENCE!

1)function removeFromCart(item) {
2) var found = false;
3)
4) for (var key in cart) {
5) var theItem = Object.keys(cart[key]).toLocaleString();
6)
7) if ( item === theItem ) {
8) found = true;
9) cart.splice(Number(key), 1);
10) }
11) }
12)
13) if ( !found ) {
14) console.log( "That item is not in your cart." );
15)}
16)
17)return cart;

I declared a variable found to keep track of the item and if it was found or not.

On line 4 I begin looping through the cart array. For each item in the array I have to convert it to a string (line 5) otherwise when I try to compare the passed in item to the key in the array’s object the comparison will never pass. For example, the first element is “Watermelon”: “$72”. If I don’t convert it to a string in line 7 what will be evaluated is if ("watermelon" === Object). Not very helpful.

So, if the item that was passed in matches one of the items in the array we turn the flag found to true and delete the item from the cart. We must use Array.splice() in this case because it doesn’t leave a hole in the array where this object once was. The index of the array is returned as a string so we must convert it to a number in order to use the splice method.

Finally, if the item is not found I just send a message back to the user saying so. In both cases, I return either the altered or unaltered shopping cart.

Lesson Learned

If the code works in one place but not another make sure the test is set up properly!

Excellent learning experience! I’m moving onto the DOM now.

Leave a Reply