3

How to get next (120), previous (122) object? Currently at second object, 141. Also, I have control on the JSON format.

var articleId = 141;

var url = {
    "Article": [
        {
            "Id": "122",
            "Title": "Article #122"
        },
        {
            "Id": "141",
            "Title": "Article #141"
        },
        {
            "Id": "120",
            "Title": "Article #120"
        }
    ]
};

$.each(url.Article, function (i, data) {
    var current = data.Id;

    if (current == articleId)
        console.log(this.Title)

   //next
   //previous
});
2
  • search forEach in javascript, that may help you
    – xkeshav
    Commented Oct 7, 2014 at 4:52
  • All good method. I'll go the one with null checking.
    – baker
    Commented Oct 7, 2014 at 16:30

4 Answers 4

1

The variable i in your code sample is actually the index into url.Article that you are currently on. Using this variable you can easily find the next and previous object.

As an example...

var prev = i > 0 ? url.Article[i - 1] : null;
var next = i < url.Article.length - 1 ? url.Article[i + 1] : null;
0

Like this, with added verification to check whether a previous or next article exists.

$.each(url.Article, function (i, data) {
    var currentId = data.Id;

    if (currentId == articleId)
        console.log(data.Title)

    var previous = i > 0 ? url.Article[i-1] : null;
    var next = url.Article.length > i+1 ? url.Article[i+1] : null;
});
0
0

i refers to the current index that you are in. So you can use i+1 and i-1 to refer to next and prev index respectively. Do like

$.each(url.Article, function (i, data) {
    var current = data.Id;

    if (current == articleId)
        console.log(this.Title);

   //next
   console.log(url.Article[i-1]);
   //previous
   console.log(url.Article[i+1]);
});
0

Try

var p = $.grep(url.Article, function (data, i) {  
      return data.Id == articleId 
             && url.Article.length === 3 
             ? data : null
}, true), prev = p[0], next = p[1]; 

console.log(prev.Id, next.Id)

jsfiddle http://jsfiddle.net/guest271314/eb6zs5mq/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.