如何将 javascript 对象数组从一种格式排列为另一种格式
How do I arrange a javascript array of objects from one format to another
我觉得这是一个非常简单的答案,但我很难理解。
我想转这个对象数组:
[{
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() 函数,但没有取得任何进展。
感谢您抽出宝贵时间。
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)
使用 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])
因为客户永远是一样的,所以你可以让 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])
我觉得这是一个非常简单的答案,但我很难理解。
我想转这个对象数组:
[{
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() 函数,但没有取得任何进展。
感谢您抽出宝贵时间。
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)
使用 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])
因为客户永远是一样的,所以你可以让 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])