我觉得这是一个非常简单的答案,但是我很难弄清楚。
我想旋转这个对象数组:
[{
client: 'lalala@email.com',
amount: 0,
date: '2018-12'
},
{
client: 'lalala@email.com',
amount: '30',
date: '2018-11'
}, {
client: 'lalala@email.com',
amount: '5',
date: '2018-10'
}]
对此:
[{
client: 'lalala@email.com',
'2018-12': 0,
'2018-11': '30',
'2018-10': '5'
}]
我一直在尝试用reduce()函数,但是没有靠近任何地方。
感谢您抽出宝贵的时间。
答案 0 :(得分:4)
reduce
是正确的方法-以下是操作方法:
const data = [{
client: 'lalala@email.com',
amount: 0,
date: '2018-12'
},
{
client: 'lalala@email.com',
amount: '30',
date: '2018-11'
}, {
client: 'lalala@email.com',
amount: '5',
date: '2018-10'
}]
const result = data.reduce((memo, {client, date, amount}) => {
memo.client = client;
memo[date] = amount;
return memo;
}, {});
console.log(result)
答案 1 :(得分:1)
使用Array.prototype.reduce
可以起作用:
const a = [{
client: 'lalala@email.com',
amount: 0,
date: '2018-12'
}, {
client: 'lalala@email.com',
amount: '30',
date: '2018-11'
}, {
client: 'lalala@email.com',
amount: '5',
date: '2018-10'
}]
const b = a.reduce((acc, {date, amount}) => {
return { ...acc, [date]: amount }
}, { client: a[0].client })
console.log([b])
答案 2 :(得分:1)
由于客户端总是一样的,因此您可以在Object.assign
中投入reduce()
来做好工作:
const data = [{client: 'lalala@email.com',amount: 0,date: '2018-12'},{client: 'lalala@email.com',amount: '30',date: '2018-11'}, {client: 'lalala@email.com',amount: '5',date: '2018-10'}]
const result = data.reduce((obj, {client, date, amount}) =>
Object.assign(obj, {client, [date]:amount}), {});
console.log([result])