简体   繁体   English

如何从对象数组的属性返回数组

[英]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: 我尝试使用map函数,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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