簡體   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