Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Grabbing object value from last index in nested array

I am making a recipe app with react and am incorperating a button to load more results at the bottom of the page. I have a data structure that looks like:

const data = [
  [_links: {...}, hits:{...}],
  [_links: {...}, hits:{...}],
  [
    _links: {
      next: {
        title: "Next",
        href: "*endPoint*"
      }
    },
    hits: {...}
  ]
]

When the button at the bottom of the component is clicked it adds the newly fetched data to the data array with the previous fetch. I want to grab the href that’s nested in the _links object from the last array inside the data array.

I am using a variable to grab it like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const nextPage = data[data.length - 1]._links.next.href

When I console log nextPage I get what I am expecting, but I keep getting Uncaught TypeError: Cannot read properties of undefined (reading '_links') that’s breaking the page.

What is the correct way to grab the href from the last array in the data array?

>Solution :

data is an array of arrays of objects,

You can use Array.prototype.flat() to have 1 level of array and then Array.prototype.at() and get the last index of the array:

const data = [
  [{_links: {}, hits:{}}],
  [{_links: {}, hits:{}}],
  [{
    _links: {
      next: {
        title: "Next",
        href: "*endPoint*"
      }
    },
    hits: {}
  }]
]

console.log(data.flat().at(-1)._links.next.href);

Array.prototype.at()
Array.prototype.flat()

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading