[英]How can I format the response coming from the server as given below using js array methods such as map(), reduce(), filter() and etc?
This is the response object from an API that I need to reformat:这是来自我需要重新格式化的 API 的响应对象:
const data = {
id: 12,
currency: "USD",
transactions: [
{
from_wallet_id: 14,
transaction_amount: '30.00',
type: 'income',
"date": "2019-12-04T06:45:49.394000+06:00"
},
{
from_wallet_id: 11,
transaction_amount: '50.00',
type: 'expenses',
date: "2019-12-04T06:45:49.394000+06:00"
},
{
from_wallet_id: 11,
transaction_amount: '70.00',
type: 'transfer',
date: "2019-12-06T06:45:49.394000+06:00"
},
{
from_wallet_id: 14,
transaction_amount: '40.00',
type: 'transfer',
date: "2019-12-08T06:45:49.394000+06:00"
},
]
}
I need to change it to the example given below (using array methods such as reduce, map, filter, etc) A little bit information: income is sum of transactions at that date.我需要将其更改为下面给出的示例(使用reduce、map、filter 等数组方法) 一点信息:收入是该日期的交易总和。 expenses is sum of transactions at that date.
费用是当日交易的总和。 type "transfer" can be income or expense If type is "transfer" and from_wallet_id is not equals to data.id then it will be added to income otherwise it will be added to expenses
type "transfer" 可以是收入或费用 如果 type 是 "transfer" 并且 from_wallet_id 不等于 data.id 那么它将被添加到收入中否则它将被添加到费用中
formattedObject = {
"2019-12-04": {
date: "2019-12-04",
income: 30,
expenses: 50
},
"2019-12-06": {
date: "2019-12-06",
income: 0,
expenses: 70
},
"2019-12-08": {
date: "2019-12-08",
income: 40,
expenses: 0
}
}
You could reduce the array nad take an adjustment for type: 'transfer'
.您可以减少数组并调整
type: 'transfer'
。
const data = { id: 12, currency: "USD", transactions: [{ from_wallet_id: 14, transaction_amount: '30.00', type: 'income', date: "2019-12-04T06:45:49.394000+06:00" }, { from_wallet_id: 11, transaction_amount: '50.00', type: 'expenses', date: "2019-12-04T06:45:49.394000+06:00" }, { from_wallet_id: 11, transaction_amount: '70.00', type: 'transfer', date: "2019-12-06T06:45:49.394000+06:00" }, { from_wallet_id: 14, transaction_amount: '40.00', type: 'transfer', date: "2019-12-08T06:45:49.394000+06:00" }] }, result = data.transactions.reduce((r, { from_wallet_id, transaction_amount, type, date }) => { date = date.slice(0, 10); if (type === 'transfer') type = data.id === from_wallet_id ? 'expenses' : 'income'; r[date] = r[date] || { date, income: 0, expenses: 0 }; r[date][type] += +transaction_amount; return r; }, {}); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.