简体   繁体   中英

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.

You are quite close.

use

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM