我一直在努力解决这个问题。
所以基本上,我有这个数据(虚拟)
[
{ user_id: 1, balance: 50, job: 'programmer' },
{ user_id: 1, balance: 20, job: 'teacher' },
{ user_id: 1, balance: 15, job: 'doctor' },
{ user_id: 2, balance: 5, job: 'doctor' },
{ user_id: 2, balance: 20, job: 'teacher' },
{ user_id: 3, balance: 100, job: 'teacher' },
{ user_id: 3, balance: 35, job: 'accountant' },
{ user_id: 3, balance: 40, job: 'lawyer' }
{ user_id: 3, balance: 10, job: 'programmer' }
{ user_id: 4, balance: 45, job: 'lawyer' }
]
我想减少/将数组分组为这样
[
{ user_id: 1, data: [{ balance: 50, job: 'programmer' }, { balance: 20, job: 'teacher' }, { balance: 15, job: 'doctor' }] },
{ user_id: 2, data: [{ balance: 5, job: 'doctor' }, { balance: 20, job: 'teacher' }] },
{ user_id: 3, data: [{ balance: 100, job: 'teacher' }, { 3, balance: 35, job: 'accountant' }, { balance: 40, job: 'lawyer' }, { balance: 10, job: 'programmer' }] },
{ user_id: 4, data: [{ balance: 45, job: 'lawyer' }] }
]
我一直在尝试使用.reduce
array.reduce((acc, obj) => {
const value = obj['user_id'];
acc[value] = (acc[value] || []).concat(obj);
return acc;
});
但是它没有返回我所期望的。
请帮助。
非常感谢您。
答案 0 :(得分:3)
您可以将Map
和对象的一部分作为结果集。
var array = [{ user_id: 1, balance: 50, job: 'programmer' }, { user_id: 1, balance: 20, job: 'teacher' }, { user_id: 1, balance: 15, job: 'doctor' }, { user_id: 2, balance: 5, job: 'doctor' }, { user_id: 2, balance: 20, job: 'teacher' }, { user_id: 3, balance: 100, job: 'teacher' }, { user_id: 3, balance: 35, job: 'accountant' }, { user_id: 3, balance: 40, job: 'lawyer' }, { user_id: 3, balance: 10, job: 'programmer' }, { user_id: 4, balance: 45, job: 'lawyer' }],
result = Array.from(
array.reduce((m, { user_id, ...rest }) =>
m.set(user_id, [...(m.get(user_id) || []), rest]), new Map),
([user_id, data]) => ({ user_id, data })
);
console.log(result);
答案 1 :(得分:1)
您可以简单地将Object
用作累加器,将user_id
用作键,然后相应地添加值
let arr =[{ user_id: 1, balance: 50, job: 'programmer' },{ user_id: 1, balance: 20, job: 'teacher' },{ user_id: 1, balance: 15, job: 'doctor' },{ user_id: 2, balance: 5, job: 'doctor' },{ user_id: 2, balance: 20, job: 'teacher' },{ user_id: 3, balance: 100, job: 'teacher' },{ user_id: 3, balance: 35, job: 'accountant' },{ user_id: 3, balance: 40, job: 'lawyer' },{ user_id: 3, balance: 10, job: 'programmer' },{ user_id: 4, balance: 45, job: 'lawyer' },]
let op = arr.reduce((acc,{user_id,...rest}) => {
acc[user_id] = acc[user_id] || {user_id,data:[]}
acc[user_id].data.push({...rest})
return acc;
},{});
console.log(Object.values(op))
答案 2 :(得分:1)
您非常亲密:
const hash = array.reduce((acc, obj) => {
const value = obj.user_id; // typo?
acc[value] = acc[value] || { user_id: obj.user_id, data: [] }; // initialize to an object
acc[value].data.push(obj);
return acc;
}, {}); // <- use a plain object as accumulator
const result = Object.values(hash); // turn back into array