简体   繁体   中英

How to grab the previous and next id from an array

I'm trying to create next and previous buttons for my blog page. My blogs posts are stored within a table in my MySQL database. At the moment I'm getting the following result.

So I can get the current id and current title , but I'm not sure how to go about displaying the previous and next one on a page.

JavaScript code:

router.get('/posts/:permalinkSlug', async(req, res, next) => {
  try {
    var blogPostArray = []
    var results = await _db.rawSql('SELECT id, permalink_slug FROM blog_posts')
    blogPostArray.push(results)

    const permalinkSlug = req.params.permalinkSlug
    const post = await postTools.getPostByPermalinkSlug(permalinkSlug)
    res.locals.current_id = post.id
    console.log(res.locals.current_id)
    console.log(permalinkSlug)

    for (i = 0; i < blogPostArray.length; i++) {
      console.log(blogPostArray[i])
    }

    if (post) {
      res.render('post/post', {
        post: post,
        page: await _db.findOne('posts', {})
      })
    } else next()
  } catch (err) {
    next(err)
  }
})

New code:

var results = await _db.rawSql('SELECT id FROM blog_posts')
console.log(results)

Result:

[
  RowDataPacket { id: 12 },
  RowDataPacket { id: 13 },
  RowDataPacket { id: 14 },
  RowDataPacket { id: 15 } 
]

If res.locals.current_id is giving a value then following will do the trick.

Replace this code like this:

blogPostArray.push(JSON.parse(JSON.stringify(results)));

This is a bug as methioned here .

 var blogPostArray = [{ id: 12, permalink_slug: 'title1' }, { id: 13, permalink_slug: 'title2' }, { id: 14, permalink_slug: 'title3' }, { id: 15, permalink_slug: 'title4' } ]; var res = { locals: { current_id: 14 } }; var index = blogPostArray.findIndex(x => Number(x.id) == Number(res.locals.current_id)); var next = getNext(index); var prev = getPrev(index); console.log(prev, next); function getNext(sr) { sr = Number(sr); if (sr + 1 == blogPostArray.length) { return {} } return blogPostArray[sr + 1];//if not working try using blogPostArray[0][sr + 1] or blogPostArray[1][sr + 1] } function getPrev(sr) { sr = Number(sr); if (sr - 1 == -1) { return {} } return blogPostArray[sr - 1];//if not working try using blogPostArray[0][sr - 1] or blogPostArray[1][sr - 1] } 

inside the loop you can use the code as follows:

for (i = 0; i < blogPostArray.length; i++) {
  console.log(getNext(i))
  console.log(getPrev(i))
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM