Solution Review: Return the Cat

This lesson will explain the solution to the problem in the previous lesson.

We'll cover the following...

Solution #

Press + to interact
function returnNthCat(n){
const state = {
cats : [
{catId : 1 , name : "tom"},
{catId : 2 , name : "tiggy"},
{catId : 3 , name : "leo"},
{catId : 4 , name : "tommy"}
],
curpage : 3
}
const { cats: { [n]:{name:thisCatName}}} = state;
return thisCatName
}
console.log(returnNthCat(1))
console.log(returnNthCat(0))
console.log(returnNthCat(3))
console.log(returnNthCat(2))

Explanation #

Let’s discuss the solution step-by-step.

On line 2, we have the state object.

const state = {
   cats : [
      {catId : 1 , name : "tom"},
      {catId : 2 , name : "tiggy"},
      {catId : 3 , name : "leo"},
      {catId : 4 , name : "tommy"}
   ],
   curpage : 3
}

As you can ...