javascript - 如何使用 JavaScript 访问 JSON 数据中嵌套数组中的特定元素?
问题描述
我有 JSON 数据,其结构如下。意图是查找特定的数据点,例如年利润,即 5000。
我想通过按名称查找列来做到这一点,例如“利润”,识别列索引(示例中为 3),然后使用列索引选择第二个节点中的第 n 个(3rd)元素(“annual” ) 的“数据”数组。
如何使用findIndex()
Javascript 中的函数执行此操作(请参阅下面我的代码的关键部分)?
JSON数据:
{
"datatable": {
"data": [
[
"AAPL",
"quarterly",
1000,
2000
],
[
"AAPL",
"annual",
5000,
10000
]
],
"columns": [{
"name": "ticker"
"type": "String"
},
{
"name": "timedim"
"type": "String"
},
{
"name": "profit",
"type": "Integer"
},
{
"name": "revenue",
"type": "Integer"
}
]
}
}
JavaScript 代码:
// daten contains the "data" array of the JSON dataset
// spalten contains the "columns" array of the JSON dataset
var i = spalten.findIndex(obj => obj.name == "profit");
output += '<p>Annual profit AAPL: ' + daten[i] + '</p>';
elroot.innerHTML += output;
解决方案
根据您提供的 JSON 结构,以下将起作用。如果您想根据参数获得特定的利润,编写一个函数会很好。
var output = ""
function getProfit(type="annual", column=2) {
var arrForType = yourData.datatable.data.find(arr => arr.indexOf(type) !== -1);
return arrForType[column];
}
var i = yourData.datatable.columns.findIndex(obj => obj.name == "profit");
output += '<p>Annual profit AAPL: ' + getProfit("annual", i) + '</p>';
document.body.innerHTML += output;
推荐阅读
- java - 使用 Visual Studio Code 在 Java 中自动生成接口方法
- apache-nifi - NiFi:将数据从 Kafka 插入到 Cassandra 的最佳流程?
- javascript - 为什么我在打字稿中没有收到有关 StrictNullChecks 的警告
- r - 使用 mgcv::gam 进行非标准评估
- c# - 使用自定义属性保存设置
- sql - Oracle Merge into ... 当不匹配时插入 ... - 我可以使用 Alias
- python-3.x - 将 ImageDataGenerator.fit 用于“featurewise_std_standardization”、“zca_whitening”等参数
- sql-server - 如何在 VB NET 函数中正确地在某个时间间隔(定时器)刷新 SQL Server 中的数据
- angular - Angular 2 scrollIntoView 不滚动
- python - 动态编程:递归+记忆 vs 循环+列表