我正在尝试从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;
}
答案 0 :(得分:1)
使用相同的currencyCode
,您还可以缩小数组和嵌套数组。
var data = { data: { Country: [{ Area: "Urban", Date: "2019-10-14T12:14:20.170Z", income: [{ amount: "33", currencyCode: "USD" }, { amount: "10", currencyCode: "INR" }], expenditure: [{ amount: "5", currencyCode: "INR" }], tax: [{ amount: "10", currencyCode: "USD" }, { amount: "10", currencyCode: "INR" }] }, { Area: "Rural", Date: "2019-10-14T12:14:20.170Z", income: [{ amount: "2", currencyCode: "USD" }, { amount: "20", currencyCode: "INR" }], loan: [{ amount: "5", currencyCode: "INR" }], tax: [{ amount: "10", currencyCode: "USD" }, { amount: "50", currencyCode: "INR" }] }] } },
result = data.data.Country.reduce((r, o) => {
Object.entries(o).forEach(([k, v]) => {
if (!Array.isArray(v)) return;
v.reduce((q, { amount, currencyCode }) => {
var temp = q.find(t => t.currencyCode === currencyCode);
if (!temp) q.push(temp = { amount: 0, currencyCode });
temp.amount = (+temp.amount + +amount).toString();
return q;
}, r[k] = r[k] || []);
});
return r;
}, { "Area": "combined" });
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }