Search⌘ K

Solution Review: Return the Cat

Explore how to use JavaScript object and array destructuring to retrieve the name property of the nth cat from an array within a state object. Understand step-by-step how to access nested objects and return a value efficiently, enhancing your coding interview skills on language basics.

We'll cover the following...

Solution #

Javascript (babel-node)
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 see, it has an array of ...