在一个关联数组中
js: array with in an associative array
我正在尝试为以下数据建立一个关联数组:
name date alpha beta
Andrew 12/08/07 2.3 1.4
5/12/07
26/03/08
____________________________________
Fred 3/09/07 2.1 1.1
23/01/08
____________________________________
基本上,每个病人都有一个名字和alpha, beta值,但他们看医生的多个日期。我在想类似下面的东西,其中名称是主键,日期存储在数组中,alpha, beta是与键相关的浮点值。
var info = [{ name: [{ dates: [ ], alpha: float, beta: float }] }];
,然后在读取CSV文件时填充这个信息数组。初始化这种关联数组的正确格式是什么?或者还有什么其他数据结构是表示这种数据的好方法?
提前感谢!
编辑:因为每个病人都有一个唯一的名字,而不是使用数组,您应该考虑使用单个对象,其中每个病人都是由对象键标识的对象,例如:
var patientList = {
andy: {},
bob: {}
};
要将CSV文件中的数据放入此结构中,您可以考虑这样做:
var csv = 'Andrew't12/08/07't1.2't3.4'nAndrew't15/09/08't1.2't3.4'nAndrew't14/08/07't1.2't3.4't'nBob't18/09/08't1.2't3.4'nAndrew't21/08/07't1.2't3.4'nDavid't31/09/08't1.2't3.4'nAndrew't22/08/07't1.2't3.4't'nSam't26/09/08't1.2't3.4';
// Split the CSV file at the carriage return.
var data = csv.split(''n');
// Recursive over the data with `map`, splitting each line up
// on the tabs and returning a patient object for each.
data = data.map(function (el) {
var patient = el.split(''t');
return {
name: patient[0],
date: patient[1],
alpha: patient[2],
beta: patient[3]
}
});
function getListOfPatientNames(arr) {
var newarr = [];
// For each patient object return the patient name only
newarr = arr.map(function (patient) {
return patient.name;
});
// A quick way of filtering out duplicates
return newarr.filter(function(elem, pos) {
return newarr.indexOf(elem) == pos;
});
}
// Return a unique list of names, and sort them.
var names = getListOfPatientNames(data).sort();
var patientList = {};
for (var i = 0, l = data.length; i < l; i++) {
var name = data[i].name;
// If the patient name doesn't exist in patientList yet
if (!patientList[name]) {
// Add a new patient object using the name as the key
var newPatient = {
dates: [data[i].date],
alpha: data[i].alpha,
beta: data[i].beta
};
patientList[name] = newPatient;
} else {
// If the patient already exists push the date to the dates array
patientList[name].dates.push(data[i].date);
}
}
术语"关联数组"几乎从不在JavaScript中使用;您可以使用对象(有时称为"映射"或"字典")来存储名称/值信息,或使用数组来存储有序数据。
看起来你想要一个病人对象的数组,像这样:
var patients = [
{
name: "Andrew",
dates: [/*...the dates...*/],
alpha: 2.3,
beta: 1.4
},
{
name: "Fred",
dates: [/*...the dates...*/],
alpha: 2.1,
beta: 1.1
}
];
根据您的需要,您可能希望也可能不希望使用构造函数来创建这些对象,但是对于您提供的简单数据,可能没有必要。
相关文章:
- 多维关联数组的最后一个索引
- node.js/javascript/couchdb视图到关联数组似乎不起作用
- 具有关联数组数据集的D3.js表
- 后关联数组使用jquery ajax
- 返回一个关联数组,而不是mongoose中的文档数组
- 如何在 Angular JS 中从关联数组创建多个复选框
- 存储在变量中的关联数组中的访问键
- 如何在具有相同 ID 的 Javascript 中按排序函数对关联数组进行排序
- 在主要的JavaScript引擎中,在JavaScript关联数组(动态对象属性)中检索/插入的复杂性是多少
- 关联数组,并使用父数组d作为selection.data()的源数组
- 获取关联数组的标签
- JavaScript:如何在最接近值的关联数组中查找键
- 单击时显示关联数组的元素
- 关联数组 - 使用图像滑块显示键值
- Javascript从关联数组中查找最低数字(气泡排序方法)
- AngularJS过滤器不适用于我的数据:关联数组
- 获取关联数组中当前函数的键
- 如何按一个仍保持字母顺序的特性值(另一个特性值)对关联数组进行排序
- 正在检查JavaScript中是否存在关联数组
- 将数据附加到关联数组或维度数组