javascript存储相似的值

时间:2013-09-18 03:18:29

标签: javascript arrays

我有一个从sql数据库

设置的列表
 Team     Name    Date Joined
 TeamA    David   June 3
 TeamB    Mike    July 2
 TeamC    Mark    June 7
 TeamA    Lisa    July 2
 TeamA    Stacy   June 7
 TeamB    Tracy   July 2
 TeamC    Joe     June 3

我希望能够存储列表并使用javascript打印TeamA或TeamB或TeamC中加入的所有人员和日期。我不知道如何处理这个问题,正在考虑数组,但不认为这不会达到我的目标,因为不确定如何将所有项目组合在一起......是否有人有想法

2 个答案:

答案 0 :(得分:1)

如果您只想存储每个团队成员的名称,那么您可以使用:

var Teams = {
    TeamA: ["David", "Lisa", "Stacy"],
    TeamB: ["Mike", "Tracy"],
    TeamC: ["Mark", "Joe"]
};

如果要将这些值打印到浏览器控制台

for (team in Teams){
    console.log(team+" : "+Teams[team].join(", "));
}

答案 1 :(得分:1)

您可以将团队定义为对象数组:

var arr = [

 {"team":"TeamA", "name":"David"},
 {"team":"TeamB", "name":"Mike"},
 {"team":"TeamC", "name":"Mark"},
 {"team":"TeamA", "name":"Lisa"},
 {"team":"TeamA", "name":"Stacy"},
 {"team":"TeamB", "name":"Tracy"},
 {"team":"TeamC", "name":"Joe"}

]

它非常灵活,您可以根据需要添加任意数量的团队/人员。然后你可以定义一个简单的过滤函数:

var teamFilter = function(obj) {
    return obj.team == this.criteria;
}

你可以调用它来创建这样的新过滤数组:

arr.criteria = "TeamA";

var arrTeamA = arr.filter(teamFilter, arr);

演示:http://jsfiddle.net/6f2NN/