Skip to main content

Retrieving properties of the object


const user = {
id: 1,
name: "Solo Stroup",
age: 39
};

const key = "id";
user[key]; // 1

I mean, you could probably just do a user.id and get the result, but what if you wanted to dynamically call it, such as in a function?

const getValue = (user, keyToRead) => {
return user[keyToRead];
}

// Sample usage
getValue({id: 2, name: "Solo"}, "name"); // "Solo"
getValue({id: 2, name: "Solo"}, "id"); // 2

Object.keys(obj)


MDN Docs The Object.keys(obj) method returns an array of all the keys in the obj that you provide.

The name of this function is Object.keys() and you can refer to it as such.

const user = {
id: 1,
name: "Sam Green",
age: 20
};

const keys = Object.keys(user);
console.log(keys); // ["id", "name", "age"]

Looping through an object to get the values for the keys


const settings = {
theme: "Dark",
version: "2.4.1",
beta: false
};

const keys = Object.keys(settings);
console.log(keys); // ["theme", "version", "beta"]
keys.forEach(key => {
// log the value of every key dynamically
console.log(settings[key]);
});

Recap


  • You cannot use the dot syntax when the property you're trying to read is stored in a variable or the result of an expression (dynamic).
  • Instead, you should use square brackets with the name of the variable inside. For example [key].
  • object[key] will evaluate the key expression first and then read the property based on its result.
  • The Object.keys(obj) method returns an array of all the keys in the obj that you provide.

Try it


/**
* @param {Object} course
* @param {number} course.id
* @param {string} course.name
* @param {number} course.year
* @param {string} detail
*/
const getCourseDetail = (course, detail) => {
return `The course ${detail} is ${course[detail]}` //<-- this iterates through whatever the property is stored in `detail`

}


// Sample usage - do not modify
console.log(getCourseDetail({id: 1, name: "Learn JavaScript", year: 2021}, "name")); // "The course name is Learn JavaScript"
console.log(getCourseDetail({id: 1, name: "Learn JavaScript", year: 2021}, "year")); // "The course year is 2021"

Find the number of keys an object has


const getCountProperties = course => {
return Object.keys(course).length

}

Return all the keys and map them to uppercase


/**
* @param {Object} course
* @param {number} [course.id]
* @param {string} [course.name]
* @param {number} [course.year]
*/
const getUpperCasedProperties = course => {
const keys = Object.keys(course);
return keys.map((thing) => thing.toUpperCase());
}

// Sample usage - do not modify
console.log(getUpperCasedProperties({id: 1, name: "Learn JavaScript", year: 2021})); // ["ID", "NAME", "YEAR"]
console.log(getUpperCasedProperties({name: "Learn JavaScript", category: "Programming"})); // ["NAME", "CATEGORY"]
console.log(getUpperCasedProperties({})); // []

Get the Values


const logValues = course => {
Object.keys(course).forEach(key => {
console.log(course[key]);
});
}

//or you can do an Object.values(course) but we haven't learned that yet in this tutorial :)

Object Methods


This is what happens when you try to access a property that does not exist on an object.

const person = {
id: 1,
firstName: "Solomon"
};

person.firstname; // undefined (firstname instead of firstName - capitalization counts in javascript)
person.age; // undefined

Undefined is one thing, but if you try to do something with that undefined, such as

person.age.toUpperCase(); // ❌ Uncaught TypeError: Cannot read property 'toUpperCase' of undefined

Typescript helps with this. The error isn't the toUpperCase(), it's the expression that came before it. There is no age property on the object.

[object Object]


When you see [object Object], that means you've called an entire object where it expects a string.

const person = {
id: 1,
firstName: "Solo"
};

console.log(`Hello ${person}`); // "Hello [object Object]"
console.log(`Hello ${person.firstName}; // "Hello Solo"

Object.Values()


MDN Docs

const user = {
id: 1,
name: "Solo Stroup",
age: 39
};

const values = Object.values(user);
console.log(values); // [1, "Solo Stroup", 39]

Object.entries()


MDN Docs

const user = {
id: 1,
name: "Liz Funkhouser",
age: 39
};

const entries = Object.entries(user);

// returns
[
["id", 1],
["name", "Liz Funkhouser"],
["age", 39]
]

Quick Recap


  • When you access a property that does not exist on an object, you will get undefined.
  • When you try to access a property or call a method on undefined (or an expression that evaluates to undefined), you will get an error Uncaught TypeError: Cannot read property 'X' of undefined.
  • When you see [object Object], it means that an object was used in a context that was expecting a string. So the .toString() method has been called automatically on the object.
  • The Object.values() method returns an array of the values of an object.
  • The Object.entries() method returns an array of arrays representing every key/value pair.
  • We will revisit Object.entries() later in this course.

Try it


Complete the function getUpperCasedValues such that it returns an array containing every property value in the course parameter it receives. Every property value should be in upper case. Check the sample usage to see the expected output.

const getUpperCasedValues = course => {
const values = Object.values(course);
return values.map((thing) => thing.toUpperCase());
return upperValues;
}

console.log(getUpperCasedValues({name: "Learn JavaScript"})); // ["LEARN JAVASCRIPT"]
console.log(getUpperCasedValues({name: "Learn JavaScript", category: "Programming"})); // ["LEARN JAVASCRIPT", "PROGRAMMING"]
console.log(getUpperCasedValues({})); // []

Visualize entries


This allows you to return the entries from the object passed into the Object.entries function.

const visualizeEntries = course => {
return Object.entries(course);
}

Chapter Recap


  • You cannot use the dot syntax when the property you're trying to read is stored in a variable or the result of an expression (dynamic).
  • Instead, you should use square brackets with the name of the variable inside. For example [key].
  • object[key] will evaluate the key expression first and then read the property based on its result.
  • The Object.keys(obj) method returns an array of all the keys in the obj that you provide.
  • When you access a property that does not exist on an object, you will get undefined.
  • When you try to access a property or call a method on undefined (or an expression that evaluates to undefined), you will get an error Uncaught TypeError: Cannot read property 'X' of undefined.
  • When you see [object Object], it means that an object was used in a context that was expecting a string. So, the .toString() method has been called automatically on the object.
  • The Object.values() method returns an array of the values of an object.
  • The Object.entries() method returns an array of arrays representing every key/value pair.
  • We will revisit Object.entries() later in this course.