gpt4 book ai didi

javascript - 从 CSV 中查找值并返回结果

转载 作者:行者123 更新时间:2023-11-28 03:41:15 30 4
gpt4 key购买 nike

我正在尝试使用 Javascript 在 CSV 文件中查找值并返回其相应的值(基本上就是 VLOOKUP 在 Excel 中的作用)

我已经能够分别遵循一些将 CSV 数据拉入数组的示例,并且我已经看到了一些在数组中查找数据的示例 - 但对于我来说,我无法弄清楚如何让两者都工作。

例如,CSV 文件 Stations.csv 具有以下数据:

mac,name
69167f276e9g,LINE1
69167f276e9f,LINE2

我想要做的是从 CSV 中查找“mac”值,并返回相应的“name”值。

因此,如果我查找“69167f276e9f”,我想取回值 LINE2。

[编辑:添加我尝试使用 MauriceNino 的建议添加的代码 - 但出现错误 Uncaught TypeError: Cannot read property '1' of undefined at the line 'return result[1] ;' ]:

$.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);

})

最佳答案

这是一个可能的解决方案:

  • 它首先根据您的数据创建一个二维数组
  • 然后它会搜索第一个以指定 mac 作为第一个值的元素
  • 然后返回该数组的第二个元素

const data = `mac,name
69167f276e9g,LINE1
69167f276e9f,LINE2`;

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 - 从 CSV 中查找值并返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57286906/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com