baker
baker

Reputation: 73

Get JSON next and previous object

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
});

Upvotes: 3

Views: 2761

Answers (4)

guest271314
guest271314

Reputation: 1

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/

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97322

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;
});

Upvotes: 0

Mithun Satheesh
Mithun Satheesh

Reputation: 27845

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]);
});

Upvotes: 0

scottheckel
scottheckel

Reputation: 9244

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;

Upvotes: 1

Related Questions