【问题标题】:Create multidimensional array using map()使用 map() 创建多维数组
【发布时间】:2015-05-09 20:37:29
【问题描述】:

专家您好,
能否推荐一下:

我有两张桌子:

<tr id='firs_table'>
<td id="team">team1</td><td>45</td>
<td id="team">team2</td><td>47</td>
</tr>
<tr id='second_table'>
<td id="team">team1</td><td id="service">service name1</td><td id="count">count1</td>
<td id="team">team1</td><td id="service">service name2</td><td id="count">count2</td>
<td id="team">team1</td><td id="service">service name3</td><td id="count">count3</td>
<td id="team">team2</td><td id="service">service name1</td><td id="count">count1</td>
<td id="team">team2</td><td id="service">service name2</td><td id="count">count2</td>
</tr>

我需要创建像这样的字典:

team1: ['service name1','service name2','service name3'], [count1,count2, count3]
team2: ['service name1','service name2'], [count1,count2]

你能用 jquery 建议算法吗? 我需要该结果才能创建 RGraph 图。 提前谢谢你。

我无法提供任何 jquery 代码的工作示例,我找不到如何迭代 $("tr#first_table td"#team") 值并将其与 $("tr#second_table td"# team"),如果值相同 => 返回数组 [[$("tr#second_table td"#service")], [$("tr#second_table td"#count")] ]。

我的意思是,我找不到主意。

【问题讨论】:

  • 我们可以假设上面的每一行都有&lt;tr&gt;吗?显示的 Html 不是很有效。还请展示您尝试过的内容
  • 是的,每个显示的表格都有 :
  • 请注意,您不能在页面中重复 ID
  • 按 ID 选择只会返回一个结果,因为 ID 是唯一的。

标签: javascript jquery arrays multidimensional-array


【解决方案1】:

这应该可以满足您的需要

var res = {}
$('table tr').each(function () {
    var cellText = $(this).find('td').map(function (i, el) {
        return $(el).text();
    }).get();
    if (!res[cellText[0]]) {
        res[cellText[0]] = [[],[]];
    }
    res[cellText[0]][0].push(cellText[1]);
    res[cellText[0]][1].push(cellText[2]);    
});

如果你有标题行可以使用$('table tr:gt(0)')

DEMO

【讨论】:

    猜你喜欢
    相关资源
    最近更新 更多
    热门标签