使用JavaScript's Reduce从对象数组创建数组

Using JavaScript's Reduce to create an array from an array of objects

本文关键字:数组 对象 Reduce 创建 JavaScript 使用      更新时间:2023-10-06

所以下面的代码是我想要实现的:

var arr = [{
    name: 'foo',
    amount: 2
}, {
    name: 'foo',
    amount: 4
}, {
    name: 'foo',
    amount: 6
}, {
    name: 'foo',
    amount: 1
}, {
    name: 'foo',
    amount: 5
}, ];
var newArr = arr.reduce(function (a, b) {
    return a.push(b.amount);
}, []);
console.log(newArr); // which I'd expect to be [2, 4, 6, 1, 5]

但是这个错误:Uncaught TypeError: Object 1 has no method 'push'。我知道我可以用.forEach()做到这一点,但我想知道用.reduce() 是否可能

您需要map,而不是reduce:

amounts = arr.map(function(x) { return x.amount })

如果你想要reduce,它是这样的:

var newArr = arr.reduce(function (a, b) {
    a.push(b.amount);
    return a;
}, []);

reduce回调应该返回accumulator对象。

您有一个对象数组。因此,对象当然不知道只能应用于数组的函数push。即使这些是数组,它也不会起作用,因为push返回数组的新长度。你应该使用map而不是reduce来实现你想要做的事情。