Search⌘ K
AI Features

Solution: Objects

Explore practical solutions for working with JavaScript objects by learning how to add and remove items from arrays in objects and how to create objects that store user data through properties and methods. This lesson helps you master object manipulation for dynamic coding tasks.

We'll cover the following...

Solution 1

Here is a possible solution for adding and removing items from a list object.

Javascript (babel-node)
const myList = {
items: [],
add(item) {
this.items.push(item)
},
remove(item) {
let index = this.items.indexOf(item)
if (index !== -1) {
this.items.splice(index, 1);
}
}
}
// Adding to the list
myList.add('Apples');
console.log("Adding Apples to the list: ", myList.items)
myList.add('Bananas');
myList.add('Oranges');
console.log("Final contents of the list: ", myList.items);
myList.remove('Bananas');
console.log("After removing Bananas the list is: ", myList.items);

Explanation

  • Lines 1–2: The myList object is created with an empty items array.

  • Lines 3–5: The function add() is used to add an item to the items array. When called, it pushes the provided item to the end of the array.

  • Lines 7–12: The method remove() ...