【发布时间】:2020-02-22 10:43:20
【问题描述】:
我正在尝试从 JSON 获取数据:
{
"data": {
"Country": [
{
"Area": "Urban",
"Date": "2019-10-14T12:14:20.170Z",
"income": [
{
"amount": "33",
"currency": "USD"
},
{
"amount": "10",
"currency": "INR"
}
],
"expenditure": [
{
"amount": "5",
"currency": "INR"
}
],
"tax": [
{
"amount": "10",
"currency": "USD"
},
{
"amount": "10",
"currency": "INR"
}
]
},
{
"Area": "Rural",
"Date": "2019-10-14T12:14:20.170Z",
"income": [
{
"amount": "2",
"currency": "USD"
},
{
"amount": "20",
"currency": "INR"
}
],
"loan": [
{
"amount": "5",
"currency": "INR"
}
],
"tax": [
{
"amount": "10",
"currency": "USD"
},
{
"amount": "50",
"currency": "INR"
}
]
}
]
}
}
我想要一个通用对象来保存具有所有唯一键的数据,例如收入、支出,然后将具有相同货币的金额相加。
需要以下格式的结果:
{
"Area": "combined",
"income": [
{
"amount": "35",
"currency": "USD"
},
{
"amount": "30",
"currency": "INR"
}
],
"expenditure": [
{
"amount": "5",
"currency": "INR"
}
],
"loan": [
{
"amount": "5",
"currency": "INR"
}
],
"tax": [
{
"amount": "20",
"currency": "USD"
},
{
"amount": "60",
"currency": "INR"
}
]
}
如果尝试使用 map 和 reduce,但如果不使用 if else 语句检查对象内部是否存在值,然后执行操作,我将无法执行某些操作。
我尝试了以下方法:
jsonResponse.reduce(
// common_keys passing as hardcoded till loan ,tax etc
(result, { loan,tax}) => {
forEach(tax, value => {
const taxObj = find(result.tax, ['currency', value.currency]);
!taxObj ? result.tax.push(value) : taxObj.amount = Number(taxObj.amount) + Number(value.amount);
});
forEach(loan, value => {
const loanObj = find(result.loan, [
'currencyCode',
value.currency,
]);
!loanObj ? result.loan.push(value): loanObj.amount = Number(loanObj.amount) + Number(value.amount);
});
//repeating for other too
return result;
}
【问题讨论】:
-
到目前为止有什么努力吗?请发布您到目前为止编写的代码
-
到目前为止我的想法
-
你有一个
currency和多个currencyCode对吗? -
抱歉,只有货币放错了 json 响应
标签: javascript json ecmascript-6 reduce