use*_*351 2 javascript csv arrays jquery delimiter
我有一个用作数据源的 CSV。我需要将换行符 ('\n') 上的行拆分为一个名为 'lines' 的变量,我需要将每行中以分号 (';') 分隔的值拆分为一个名为 'items' 的变量.
我希望能够检查一行上的第一个值,如果它等于输入框中的输入值,我想将此行(在值之间使用分号分隔符)添加到名为 newData 的新变量中。如果它不等于输入框中的值,我想排除它。
我基本上想过滤掉第一个值不等于我正在搜索的值的每一行。
以下是数据示例(假设每行后有一个换行符 ('\n')):
"ID";"Date";"Time";"Status"
"1";"2013.01.01";"10:03 AM";"Active"
"1";"2013.01.05";"07:45 AM";"Active"
"2";"2013.01.03";"9:12 PM";"Active"
"2";"2013.01.11";"6:37 AM";"Inactive"
"1";"2013.01.22";"12:57 PM";"Inactive"
Run Code Online (Sandbox Code Playgroud)
我可以拆分第一个标题行,并且不会包含在我正在寻找的结果中。如果我的搜索在 ID 列上并且搜索值为 1,我只想返回 ID 等于 1 的行并希望它匹配上面的格式(无标题行)。相反,如果搜索值为 7,我将只返回无行或仅返回标题行。
到目前为止,我所能做的就是从我正在导入的数据中拆分行(我找到了所有这些代码,我真的不太熟悉 javascript 或 jQuery):
$.get("myFile.csv", function(data) {
data = data.replace(/"/g, "");
var lines = data.split('\n');
var first = lines.shift().split(';');
});
// HTML Input Box
<input id="search_box" type="text">
<button id="btn_search">Search</button>
Run Code Online (Sandbox Code Playgroud)
谢谢。
这是一个使用纯 JavaScript 的简单解决方案:
// Assuming csvString is the string given in the question
var inputArray = csvString.split('\n');
var filteredArray = inputArray.filter(function (rowString) {
return (rowString.split(";")[0] === '"1"');
});
var filteredString = filteredArray.join('\n');
Run Code Online (Sandbox Code Playgroud)
在此结束时,filteredString
将是:
"1";"2013.01.01";"10:03 AM";"Active"
"1";"2013.01.05";"07:45 AM";"Active"
"1";"2013.01.22";"12:57 PM";"Inactive"
Run Code Online (Sandbox Code Playgroud)
有关此解决方案中使用的方法如何工作的更多信息,请参阅:
这是一些执行此操作的代码,假设您知道如何使数据与lines变量中的数据相同(您说过您做到了)。您可以按任何字段和任何值进行搜索。
$(document).ready(function() {
var headers = '"ID";"Date";"Time";"Status"';
var lines = [
'"1";"2013.01.01";"10:03 AM";"Active"',
'"1";"2013.01.05";"07:45 AM";"Active"',
'"2";"2013.01.03";"9:12 PM";"Active"',
'"2";"2013.01.11";"6:37 AM";"Inactive"',
'"1";"2013.01.22";"12:57 PM";"Inactive"'
];
// these contain the name of the field you want to search in
// as defined by your header and the value to search for.
var searchField = 'ID';
var searchForThisValue = 1; // this would be a parameter in your code
var endResult =[]; // this is the stored result
var fieldIndex = -1;
$.each(headers.split(';'), function(index) {
if( this.replace(/["']/g, "") == searchField ) {
fieldIndex = index;
}
});
$.each(lines, function() {
var fields = this.split(';'); // split up by semicolon
// strip the quotes around around the numbers
if(fields[fieldIndex].replace(/["']/g, "") == searchForThisValue) {
endResult.push(this);
}
});
// do whatever you want with your result, here I have just thrown
// them into an element with the id of 'blah'
$.each(endResult, function() {
$('#blah').append(this + '<br/>');
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
11231 次 |
最近记录: |