繁体   English   中英

使用JavaScript的Reduce从对象数组创建数组

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

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

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回调应该返回累加器对象。

您在那里有一系列对象。 因此,对象当然不知道只能应用于数组的功能推送。 即使这些是数组,它也不起作用,因为push返回了数组的新长度。 您应该使用map而不是reduce来实现您想做的事情。

暂无
暂无

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

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