javascript - 在 NodeJS 中迭代嵌套对象
问题描述
如何迭代动态嵌套对象
{
"2021-02-01": {
"INR": 88.345,
"CZK": 25.975,
"JPY": 126.77
},
"2021-02-02": {
"INR": 87.906,
"CZK": 25.9,
"JPY": 126.46
},
"2021-02-05": {
"INR": 87.367,
"CZK": 25.806,
"JPY": 126.72
}
}
注意:货币是动态的,可以更改为其他货币,例如“INR,CZK,JPY”,可以更改为“USD,EUR,INR”
我需要获取对象中所有货币的所有汇率的值并总结所有这些
这是我的代码(它不完整,我被困在其中)
let rates = {here is object mentioned above}
//iterating over object and pushing into array rateList
for(let keys in rates){
rateList.push(rates[keys])
}
//iterating over rateList array to get value
rateList.forEach((obj)=>{
console.log(Object.keys(obj)) //by this code i'm getting keys but how do i get value and sum it up
})
总体目标是获得所有汇率值的平均值。
解决方案
更新的答案
根据 OP 在下面的评论,仍然有一种速记方式来完成要求:
const rates = {
"2021-02-01": {
"INR": 88.345,
"CZK": 25.975,
"JPY": 126.77
},
"2021-02-02": {
"INR": 87.906,
"CZK": 25.9,
"JPY": 126.46
},
"2021-02-05": {
"INR": 87.367,
"CZK": 25.806,
"JPY": 126.72
}
};
var returnObject = {};
Object.values(rates).forEach(childObject => { // loop all child objects within parent `rates` object:
for (const [key, value] of Object.entries(childObject)) // extract each key=>value pair
returnObject[key] = typeof returnObject[key] === 'undefined' ? value : returnObject[key] + value; // track it in `returnObject` - checks if the currency code already exists as a key in returnObject - if so, sums the current value and all previously-encountered values - if it doesn't already exist as a key in returnObject, sets the key to the current value
});
console.dir(returnObject);
原始答案
const rates = {
"2021-02-01": {
"INR": 88.345,
"CZK": 25.975,
"JPY": 126.77
},
"2021-02-02": {
"INR": 87.906,
"CZK": 25.9,
"JPY": 126.46
},
"2021-02-05": {
"INR": 87.367,
"CZK": 25.806,
"JPY": 126.72
}
};
for (var key of Object.keys(rates)) { // loop all dates in parent `rates` object:
rates[key] = Object.values(rates[key]).reduce((acc, cv) => acc += cv); // extract the values for all keys in the child Object into an Array, then use reduce() to sum the values; finally, replace the initial child object with the float result of the summation
}
console.dir(rates);
进一步阅读:
推荐阅读
- mysql - 查询卡在 Mariadb 10.1 中
- python - MLPRegressor (scikit) 的回归问题
- apache-spark - 如何从 PyCharm 连接 Databricks 社区版集群
- django - 将 Django (DRF) 连接到现有数据库
- openxml-powertools - MetricsGetter.GetTextWidth 的定义在哪里
- kotlin - 在 Javalin 处理程序中调用 Junit 断言时不起作用
- reactjs - 做什么
`React.Component 中的意思 ` - php - TCPDF:图像未正确显示在 PDF 中
- r - 如何将 csv 文件导入使用 R 内核的 Google Colab?
- c++ - C/C++ 将 8 字节数组转换为 64 位整数