At their most basic, objects are just collections of key-value pairs, or in other words, pieces of data mapped to unique identifiers that we call properties or keys. Let’s take a look at a very simple example:

let FCC_User = {
  username: 'awesome_coder',
  followers: 572,
  points: 1741,
  completedProjects: 15
};

The above code defines an object called FCC_User that has four properties, each of which map to a specific value. If we wanted to know the number of followers FCC_User has, we can access that property by writing:

let userData = FCC_User.followers;
// userData equals 572

This is called dot notation. Alternatively, we can also access the property with brackets, like so:

let userData = FCC_User['followers']
// userData equals 572

Notice that with bracket notation, we enclosed followers in quotes. This is because the brackets actually allow us to pass a variable in to be evaluated as a property name (hint: keep this in mind for later!). Had we passed followers in without the quotes, the JavaScript engine would have attempted to evaluate it as a variable, and a ReferenceError: followers is not defined would have been thrown.

Task

Using the same syntax, we can also add new key-value pairs to objects. We’ve created a foods object with three entries. Add three more entries: bananas with a value of 13, grapes with a value of 35, and strawberries with a value of 27.

let foods = {
  apples: 25,
  oranges: 32,
  plums: 28
};

// change code below this line

// change code above this line

console.log(foods);

Task Conditions to be satisfied

  • foods is an object
  • The foods object has a key “bananas” with a value of 13
  • The foods object has a key “grapes” with a value of 35
  • The foods object has a key “strawberries” with a value of 27
  • The key-value pairs should be set using dot or bracket notation

Solution

let foods = {
  apples: 25,
  oranges: 32,
  plums: 28
};

// change code below this line
foods.bananas = 13;
foods.grapes = 35;
foods.strawberries = 27;
// change code above this line

console.log(foods);

Notes


[Basic Data Structures] Access Property Names with Bracket Notation

In the first object challenge we mentioned the use of bracket notation as a way to access property values using the evaluation of a variable. For instance, imagine that our foods object is being used in a program for a supermarket cash register. We have some function that sets the selectedFood and we want to check our foods object for the presence of that food. This might look like:

let selectedFood = getCurrentFood(scannedItem);
let inventory = foods[selectedFood];

This code will evaluate the value stored in the selectedFood variable and return the value of that key in the foods object, or undefined if it is not present. Bracket notation is very useful because sometimes object properties are not known before runtime or we need to access them in a more dynamic way.

Task

We’ve defined a function, checkInventory, which receives a scanned item as an argument. Return the current value of the scannedItem key in the foods object. You can assume that only valid keys will be provided as an argument to checkInventory.

let foods = {
  apples: 25,
  oranges: 32,
  plums: 28,
  bananas: 13,
  grapes: 35,
  strawberries: 27
};
// do not change code above this line

function checkInventory(scannedItem) {
  // change code below this line

}

// change code below this line to test different cases:
console.log(checkInventory("apples"));

Task Conditions to be satisfied

  • checkInventory is a function
  • The foods object should have only the following key-value pairs: apples: 25, oranges: 32, plums: 28, bananas: 13, grapes: 35, strawberries: 27
  • checkInventory(“apples”) should return 25
  • checkInventory(“bananas”) should return 13
  • checkInventory(“strawberries”) should return 27

Solution

let foods = {
  apples: 25,
  oranges: 32,
  plums: 28,
  bananas: 13,
  grapes: 35,
  strawberries: 27
};
// do not change code above this line

function checkInventory(scannedItem) {
  // change code below this line
  return foods[scannedItem];
}

// change code below this line to test different cases:
console.log(checkInventory("apples"));

Notes


delete Keyword to Remove Object Properties

Now you know what objects are and their basic features and advantages. In short, they are key-value stores which provide a flexible, intuitive way to structure data, and, they provide very fast lookup time. Throughout the rest of these challenges, we will describe several common operations you can perform on objects so you can become comfortable applying these useful data structures in your programs.

In earlier challenges, we have both added to and modified an object’s key-value pairs. Here we will see how we can remove a key-value pair from an object.

Let’s revisit our foods object example one last time. If we wanted to remove the apples key, we can remove it by using the delete keyword like this:

delete foods.apples;

Task

Use the delete keyword to remove the oranges, plums, and strawberries keys from the foods object.

let foods = {
  apples: 25,
  oranges: 32,
  plums: 28,
  bananas: 13,
  grapes: 35,
  strawberries: 27
};

// change code below this line

// change code above this line

console.log(foods);

Task Conditions to be satisfied

  • The foods object only has three keys: apples, grapes, and bananas
  • The oranges, plums, and strawberries keys are removed using delete

Solution

let foods = {
  apples: 25,
  oranges: 32,
  plums: 28,
  bananas: 13,
  grapes: 35,
  strawberries: 27
};

// change code below this line
delete foods.oranges;
delete foods.plums;
delete foods.strawberries;
// change code above this line

console.log(foods);

Basic Data Structures: Check if an Object has a Property

Now we can add, modify, and remove keys from objects. But what if we just wanted to know if an object has a specific property? JavaScript provides us with two different ways to do this. One uses the hasOwnProperty() method and the other uses the in keyword. If we have an object users with a property of Alan, we could check for its presence in either of the following ways:

users.hasOwnProperty('Alan');
'Alan' in users;
// both return true

Task

We’ve created an object, users, with some users in it and a function isEveryoneHere, which we pass the users object to as an argument. Finish writing this function so that it returns true only if the users object contains all four names, Alan, Jeff, Sarah, and Ryan, as keys, and false otherwise

let users = {
  Alan: {
    age: 27,
    online: true
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: true
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function isEveryoneHere(obj) {
  // change code below this line

  // change code above this line
}

console.log(isEveryoneHere(users));

Task Conditions to be satisfied

  • The users object only contains the keys Alan, Jeff, Sarah, and Ryan
  • The function isEveryoneHere returns true if Alan, Jeff, Sarah, and Ryan are properties on the users object
  • The function isEveryoneHere returns false if Alan, Jeff, Sarah, and Ryan are not properties on the users object

Solution

let users = {
  Alan: {
    age: 27,
    online: true
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: true
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function isEveryoneHere(obj) {
  // change code below this line
  if(obj.hasOwnProperty('Alan', 'Jeff', 'Sarah', 'Ryan')){
    return true;
  }
  else {
    return false;
  }
  // change code above this line
}

console.log(isEveryoneHere(users));

Notes


[Basic Data Structures] Iterate Through the Keys of an Object with a for…in Statement

Sometimes you may need to iterate through all the keys within an object. This requires a specific syntax in JavaScript called a for…in statement. For our users object, this could look like:

for (let user in users) {
  console.log(user);
};

// logs:
Alan
Jeff
Sarah
Ryan
In this statement, we defined a variable user, and as you can see, this variable was reset during each iteration to each of the object's keys as the statement looped through the object, resulting in each user's name being printed to the console.

Note

Objects do not maintain an ordering to stored keys like arrays do; thus a keys position on an object, or the relative order in which it appears, is irrelevant when referencing or accessing that key.

Task

We’ve defined a function, countOnline; use a for…in statement within this function to loop through the users in the users object and return the number of users whose online property is set to true.

let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function countOnline(obj) {
  // change code below this line

  // change code above this line
}

console.log(countOnline(users));

Task Conditions to be satisfied

  • The users object contains users Jeff and Ryan with online set to true and users Alan and Sarah with online set to false
  • The function countOnline returns the number of users with the online property set to true

Solution

let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function countOnline(obj) {
  // change code below this line
  let count = 0;
  for (let i in obj) {
    if(obj[i].hasOwnProperty("online") && obj[i].online == true) {
      count++;
      // console.log(count);
      // console.log(obj[i]);
    }
  }
  return count;
  // change code above this line
}

console.log(countOnline(users));

Notes


[Basic Data Structures] Generate an Array of All Object Keys with Object.keys()

We can also generate an array which contains all the keys stored in an object using the Object.keys() method and passing in an object as the argument. This will return an array with strings representing each property in the object. Again, there will be no specific order to the entries in the array.

Finish writing the getArrayOfUsers function so that it returns an array containing all the properties in the object it receives as an argument.

let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function getArrayOfUsers(obj) {
  // change code below this line

  // change code above this line
}

console.log(getArrayOfUsers(users));

Task Conditions to be satisfied

  • The users object only contains the keys Alan, Jeff, Sarah, and Ryan
  • The getArrayOfUsers function returns an array which contains all the keys in the users object

Solution

let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function getArrayOfUsers(obj) {
  // change code below this line
  return Object.keys(obj);
  // change code above this line
}

console.log(getArrayOfUsers(users));

Notes


Basic Data Structures: Modify an Array Stored in an Object

Now you’ve seen all the basic operations for JavaScript objects. You can add, modify, and remove key-value pairs, check if keys exist, and iterate over all the keys in an object. As you continue learning JavaScript you will see even more versatile applications of objects. Additionally, the optional Advanced Data Structures lessons later in the curriculum also cover the ES6 Map and Set objects, both of which are similar to ordinary objects but provide some additional features. Now that you’ve learned the basics of arrays and objects, you’re fully prepared to begin tackling more complex problems using JavaScript!

Task

Take a look at the object we’ve provided in the code editor. The user object contains three keys. The data key contains five keys, one of which contains an array of friends. From this, you can see how flexible objects are as data structures. We’ve started writing a function addFriend. Finish writing it so that it takes a </code>user</code> object and adds the name of the friend argument to the array stored in user.data.friends and returns that array

let user = {
  name: 'Kenneth',
  age: 28,
  data: {
    username: 'kennethCodesAllDay',
    joinDate: 'March 26, 2016',
    organization: 'freeCodeCamp',
    friends: [
      'Sam',
      'Kira',
      'Tomo'
    ],
    location: {
      city: 'San Francisco',
      state: 'CA',
      country: 'USA'
    }
  }
};

function addFriend(userObj, friend) {
  // change code below this line  

  // change code above this line
}

console.log(addFriend(user, 'Pete'));

Task Conditions to be satisfied

  • The user object has name, age, and data keys
  • The addFriend function accepts a user object and a friend string as arguments and adds the friend to the array of friends in the user object
  • addFriend(user, "Pete") should return ["Sam", "Kira", "Tomo", "Pete"]

Solution

let user = {
  name: 'Kenneth',
  age: 28,
  data: {
    username: 'kennethCodesAllDay',
    joinDate: 'March 26, 2016',
    organization: 'freeCodeCamp',
    friends: [
      'Sam',
      'Kira',
      'Tomo'
    ],
    location: {
      city: 'San Francisco',
      state: 'CA',
      country: 'USA'
    }
  }
};

function addFriend(userObj, friend) {
  // change code below this line
  userObj.data.friends.push(friend);
  return userObj.data.friends;
  // for(let i in userObj.data.friends){
  //   console.log(userObj.data.friends[i]);
  // }
  // change code above this line
}


console.log(addFriend(user, 'Pete'));