Search⌘ K

Exercise on Objects in ES6

Explore practical exercises that help you apply ES6 object features and prototype-based inheritance in JavaScript. Learn to set default values, create and extend prototype objects, and manipulate dynamic data structures like shopping baskets with modern, concise syntax. This lesson strengthens your understanding of ES6 object capabilities through hands-on coding tasks and method implementations.

Exercise 1:

Suppose an array of firstName, email, basketValue triples are given. Create ONE JavaScript expression that puts a default value of '-' and 0 to the firstName or basketValue fields respectively, whenever the firstName or the basketValue keys are missing. Remember to name your new object, newBaskets or your code won’t run.

Javascript (babel-node)
// the baskets object is randomly generated
console.log("baskets: ");
console.log(baskets);
let newBaskets = {}

Explanation

The hard part of the solution is that we need one JavaScript expression. When it comes to transforming the value of an array, we usually use the map method. The shortest way of writing a map function is through using the arrow syntax. Inside the map, we have to fill in the default values in item. If a key is already given in item, it takes precedence. We will use Object.assign. For each element of the basket array, we will create an object of default values, and we extend it with the element of ...