user1234
user1234

Reputation: 3159

how to limit the number of values to be pushed to an array-JqueryJs

I have an json object as follows. I have an array named category that I'm trying to push some values into it. Here is the Js:

var data={
    products : [
        { type: 'fos', name: 'retek' },
        { type: 'testta', name: 'item' },
        { type: 'nyedva', name: 'blabla' }
    ]
};
var categories = [];

Now i want to push all the values into the categories array except one: here is what i tried:

$.each(data.products, function(index, mon) {
    if (mon.type == 'testta') {
        //dont push the array
    } else {
        //push it to array
    }
});

but this work..any ideas how to achieve this?? Thanks!

Upvotes: 0

Views: 60

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173572

I'm not sure why that wouldn't work, but typically this is the kind of job you can use jQuery.grep() for:

var categories = $.grep(data.products, function(mon) {
    return mon.type != 'testta';
});

Upvotes: 1

lloan
lloan

Reputation: 1403

Have you tried this:

$.each(data.products, function(index, mon){
    if(mon.type !== 'testta'){
        categories.push(mon)
    }
});

Upvotes: 1

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Try like this

$.each(data.products, function(index, mon) {   
    if (mon.type !== 'testta') {
        categories.push(mon)
    }
});
console.log(categories);

Upvotes: 0

Related Questions