【发布时间】:2019-12-08 17:53:48
【问题描述】:
我正在尝试使用 Javascript 在 CSV 文件中查找一个值并返回它的对应值(基本上是 VLOOKUP 在 Excel 中所做的)
我已经能够分别遵循一些将 CSV 数据拉入数组的示例,并且我已经看到了一些在数组中查找数据的示例 - 但对于我的生活,我无法弄清楚如何让两者都工作。
例如,CSV 文件stations.csv 有以下数据:
mac,name
69167f276e9g,LINE1
69167f276e9f,LINE2
我想做的是从 CSV 中查找 'mac' 值,并返回相应的 'name' 值。
因此,如果我查找 '69167f276e9f',我想取回 LINE2 的值。
[编辑:使用 MauriceNino 的建议添加我尝试过的代码 - 但在 'return result[1] 行出现错误 Uncaught TypeError: Cannot read property '1' of undefined ;' ]:
$.ajax('stations.csv').done(function(data) {
const lookup = (arr, mac) => {
let twoDimArr = dataArr.map(el => el.split(',')); // map it to array of arrays of strings (data)
let result = twoDimArr.filter(el => el[0] == mac)[0]; // Get the first element where the mac matches the first element in the array
return result[1]; // Return the second element in the array
};
let dataArr = data.split('\n');
dataArr .shift(); // Remove the first array element (The header)
let resultMac = lookup(dataArr, "69167f276e9f");
console.log(resultMac);
})
【问题讨论】:
-
请同时发布您的尝试
JavaScript代码。 -
完成(抱歉,这是我第一次来)
标签: javascript jquery jquery-csv