简体   繁体   English

通过 reduce 修改对象数组

[英]modify array of objects by reduce

I have an array like ->我有一个像->这样的数组

[{amount: 5000, date: "2020-04", user: "Bill Gates"}, {amount: 5000, date: "2020-04", user: "Jon Jones"}, {amount: 5000, date: "2020-05", user: "Jon Jones"}, {amount: 5000, date: "2020-05", user: "Bill Gates"}, ...]

And I want to modify it to ->我想将其修改为 ->

[{user: "Bill Gates", data: [{amount: 5000, date: "2020-04"}, {amount: 5000, date: "2020-05"}]}, {user: "Jon Jones", data: [{amount: 5000, date: "2020-04"}, {amount: 5000, date: "2020-05"}]}, ....]

I write reduce function ->我写减少 function ->

let reduced = array.reduce((sells, {user, date, amount}) => ({
    ...sells,
    user: user,
    data: [{date: date, amount: amount}],
}),{});

but it returns just one item of array.但它只返回一项数组。 How can I return all of them?我怎样才能将它们全部归还?

You can search for the user using Array.prototype.find if found that means it is already processed and you can push the data object in the existing array else create a new object and insert it in the accumulator:您可以使用Array.prototype.find搜索用户,如果发现这意味着它已被处理,您可以将数据 object 推送到现有数组中,否则创建一个新的 object 并将其插入累加器中:

 const data = [{amount: 5000, date: "2020-04", user: "Bill Gates"}, {amount: 5000, date: "2020-04", user: "Jon Jones"}, {amount: 5000, date: "2020-05", user: "Jon Jones"}, {amount: 5000, date: "2020-05", user: "Bill Gates"}]; const result = data.reduce((sells, {user, date, amount}) => { let match = sells.find(e => e.user === user); if(match){ match.data.push({amount, date}); }else{ match = {user, data: [{amount, date}]}; sells.push(match); } return sells; }, []); console.log(result);

input.reduce((acc, {user, amount, date}) => {
    const userToExtend = acc.find(u => u.user === user)
    if(userToExtend) userToExtend.data.push[{amount, date}]
    else acc.push({user, data: [{amount, date}]});
    return acc
}, []);

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

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