akifquddus
akifquddus

Reputation: 632

How to return an array from properties of an array of objects

I have an array of objects as follows:

var lanes = [
{
 "name" : "Breakfast Special",
 "className" : "breakfast-special",
 "sales" : 200,
 "redemptions" : 137
},
{
 "name" : "Free Danish",
 "className" : "free-danish",
 "sales" : 300,
 "redemptions" : 237
},
{
 "name" : "Half Price Coffee",
 "className" : "half-price-coffee",
 "sales" : 240,
 "redemptions" : 37
}];

I want to create an array that contains only numerical values stored for 'redemptions'. I can access values as:

lanes[0].redemptions;

By going through each object using a loop, but I am looking for some efficient way to do that.

I tried this using map function as follows:

var arrayRedemptions = lanes.map(function () {return this.redemptions});

But it's not working. Any help would be appreciated.

Upvotes: 0

Views: 38

Answers (3)

akifquddus
akifquddus

Reputation: 632

Just after adding extra check especially while working with Auto Generated Content:

var arrayRedemptions = array.map(function(obj) {
    if (obj) 
        return obj.redemptions;
    else
        return -1;
}); 

Upvotes: 0

Sherali Turdiyev
Sherali Turdiyev

Reputation: 1743

yeah. inside of map you can use these params(each item, index, array)

var arrayRedemptions = lanes.map(function (item, index, array) {
    return item ? item.redemptions : -1;
});

Upvotes: 2

Satpal
Satpal

Reputation: 133403

You are quite close.

use

var arrayRedemptions = lanes.map(function(obj) {
    return obj.redemptions
});

Upvotes: 2

Related Questions