简体   繁体   English

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

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

So the following code is what I'm trying to achieve: 所以下面的代码是我想要实现的:

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]

But this errors: Uncaught TypeError: Object 1 has no method 'push' . 但是会出现以下错误: Uncaught TypeError: Object 1 has no method 'push' I know I could do this with .forEach() but I'm wondering if it's possible with .reduce() 我知道我可以使用.forEach()做到这一点,但我想知道是否可以使用.reduce()

You need map , not reduce : 您需要map ,而不是reduce

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

If you want reduce , it goes like this: 如果您需要reduce ,它会像这样:

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

The reduce callback is supposed to return the accumulator object. reduce回调应该返回累加器对象。

You have an array of objects there. 您在那里有一系列对象。 So of course the objects don't know the function push which can be only applied on arrays. 因此,对象当然不知道只能应用于数组的功能推送。 Even if those were arrays it would not work because push returns the new length of the array. 即使这些是数组,它也不起作用,因为push返回了数组的新长度。 You should use map instead of reduce to achieve what you want to do. 您应该使用map而不是reduce来实现您想做的事情。

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

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