Mark
Mark

Reputation: 7818

Possible to conditionally $.map items in jQuery/Javascript

Is it possible, to add a condition to the $.map in jquery?

My code is:

var extrasToSave = $.map(self.extras(), function (extra) {
                return {
                    Descr: extra.description,
                    Pr: extra.price,
                    Cnt: extra.count()
                };
            });

I only want to map the object, if extra.count() is a number more than 0. So pseudo code:

var extrasToSave = $.map(self.extras(), function (extra) {
           if (extra.count()>0)
             {
                return {
                    Descr: extra.description,
                    Pr: extra.price,
                    Cnt: extra.count()
                };
              }
            });

Thank you,

Mark

Upvotes: 1

Views: 4576

Answers (2)

Andy
Andy

Reputation: 63524

You don't even have to use jQuery's map function if you don't want to. From the looks of your code you're just mapping an array of objects, so use can use the native JS map and filter functions.

var extrasToSave = arr
  .filter(function (el) { return el.count()  > 0; })
  .map(function (el) {
     return {
        Descr: el.description,
        Pr: el.price,
        Cnt: el.count()
    }
  });

Upvotes: 3

Lix
Lix

Reputation: 47956

Yes, this is possible, but you'll still need to return something from your callback function. You can return null or undefined to remove the item from the resulting array. So something like this should work:

var extrasToSave = $.map( self.extras(), function ( extra ) {
  if ( extra.count() > 0 ) {
    return { 
      Descr: extra.description,
      Pr: extra.price,
      Cnt: extra.count()
    };
  } else { return undefined; }
});

Checkout the possible return values for the $.map callback in the documentation

The function can return:

  • the translated value, which will be mapped to the resulting array
  • null or undefined, to remove the item
  • an array of values, which will be flattened into the full array

Upvotes: 1

Related Questions