user9817924
user9817924

Reputation:

Javascript push to array advanced

I have simple pagination function that outputs array.

exports.pagination = function(currentPage, nrOfPages) {
    var delta = 1,
        range = [],
        rangeWithDots = [],
        l;

    range.push(1);  

    if (nrOfPages <= 1){
    return range;
    }

    for (let i = currentPage - delta; i <= currentPage + delta; i++) {
        if (i < nrOfPages && i > 1) {
            range.push(i);
        }
    }  
    range.push(nrOfPages);

    for (let i of range) {
        if (l) {
            if (i - l == 2) {
                rangeWithDots.push(l + 1);
            } else if (i - l !== 1) {
                rangeWithDots.push('...');
            }
        }
        rangeWithDots.push(i);
        l = i;
    }

    return rangeWithDots;
}

handlebars:

{{#each pagination}}
            <li class="paginator-item">
                <a href="{{this}}" class="paginator-itemLink">{{this}}</a>
            </li>
{{/each}}

output:

1 ... 7 8 9 ... 19

It works well. But what i want to do is to seperate "number" and "href" so i can use

{{#each pagination}}
            <li class="paginator-item">
                <a href="{{this.href}}" class="paginator-itemLink">{{this.number}}</a>
            </li>
 {{/each}}

But dont know how can i do this but unable. Cant find the correct way. rangeWithDots.push(number:'...',href:''). Tried lot of things but cant find that one correct

Upvotes: 0

Views: 247

Answers (2)

MTCoster
MTCoster

Reputation: 6145

You’re almost right! You just need to wrap your parameter to push as an object using {...}:

rangeWithDots.push({ number: ..., href: '...' });

Upvotes: 0

Beginner
Beginner

Reputation: 9095

you can push as an object which consist of multiple properties.

So from the array you can read by accessing the object and the corresponding property.

i hope this will solve the issue.

var rangeWithDots = []

rangeWithDots.push({href: "/sample", number: 5})

console.log(rangeWithDots)

//you can access the number by
console.log("number", rangeWithDots[0].number)

Upvotes: 1

Related Questions