在filter()方法中返回值而不是对象

时间:2016-10-06 19:10:18

标签: javascript arrays methods foreach

我有这个简单的代码:



function getStockOver(stocks) {
    'use strict';
    return stocks.filter(function (stock) {
        return (stock.price > 150);
    });
}

var stocks = [
    { symbol: 'XFX', price: 240.22, volume: 23432},
    { symbol: 'TNZ', price: 110.22, volume: 232},
    { symbol: 'JXJ', price: 340.22, volume: 5632}
];
var symbols = getStockOver(stocks);

console.log(symbols);




检查stock.price > 150.filter()是否返回,否则跳过它。 但是我想只返回通过price创建的新数组中的.filter(),而不是整个对象,如何?

注意: 我知道这可以通过.forEach()完成,但.filter()更容易。

3 个答案:

答案 0 :(得分:4)

你想要减少,而不是过滤

var stocks = [
    { symbol: 'XFX', price: 240.22, volume: 23432},
    { symbol: 'TNZ', price: 110.22, volume: 232},
    { symbol: 'JXJ', price: 340.22, volume: 5632}
];
var results = stocks.reduce( function (a,o) { if(o.price > 150) a.push(o.price); return a; }, []);
console.log(results);

答案 1 :(得分:3)

您只需为价格添加Array#map

function getStockOver(stocks) {
    'use strict';
    return stocks.filter(function (stock) {
        return (stock.price > 150);
    }).map(function (stock) {
        return stock.price;
    });
}

var stocks = [
    { symbol: 'XFX', price: 240.22, volume: 23432},
    { symbol: 'TNZ', price: 110.22, volume: 232},
    { symbol: 'JXJ', price: 340.22, volume: 5632}
];
var symbols = getStockOver(stocks);

console.log(symbols);

答案 2 :(得分:1)

您也可以在一行中完成此操作。这些内置函数就是为了这个目的而制作的。

symbols = stocks.filter(function(stock){
    return stock.price > 150
}).map(function(stock){
    return stock.price;
});

您还可以使用对象执行更复杂的操作:

var StockList = function( _data ) {
    this.data = _data;
};
StockList.prototype.getStocksOver = function( overPrice ) {
    return new StockList(this.data.filter(function (stock) {
        return stock.price > overPrice;
    }));
};
StockList.prototype.getPrices = function() {
    return this.data.map(function (stock) {
        return stock.price;
    });
};

var stocks = new StockList([
    { symbol: 'XFX', price: 240.22, volume: 23432 },
    { symbol: 'TNZ', price: 110.22, volume: 232 },
    { symbol: 'JXJ', price: 340.22, volume: 5632 }
]);

var pricesOver150 = stocks.getStocksOver(150).getPrices();

console.log(pricesOver150);