0

我觉得这是一个非常简单的答案,但我很难弄清楚。

我想把这个对象数组:

[{
    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() 函数,但没有接近。

感谢您抽出宝贵的时间。

4

3 回答 3

4

Areduce是正确的方法 - 这是如何做到的:

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)

于 2018-12-30T02:07:00.717 回答
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])

于 2018-12-30T02:12:17.770 回答
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])

于 2018-12-30T02:12:47.437 回答