在javascript中年龄相同时对名称进行分组

时间:2016-02-19 15:03:39

标签: javascript jquery arrays object

我正在使用jQuery获取成员列表,并迭代每个成员以获取名称和年龄。我想要做的是,如果它们具有相同的年龄,则将它们存储在一起。类似的东西:

{
    31: { John, Mary },
    24: { Paul, Peter } 
}

我似乎无法正确存储它们。

编辑

这是我到目前为止所做的:

$('span.members a').each(function () {
  $.ajax({
    url: $(this).attr('href'),
    success: function (result) {
      name = $(result).find('tr td:contains("Username:")').next().text().trim();
      age = $(result).find('tr td:contains("Age:")').next().text().trim();

    }
  });
});

修改

这是源HTML:

<table cellpadding="0" cellspacing="0" border="0" width="96%" class="box" id="testProf" style="border-spacing:0;">
<tr>
    <td class="top" colspan="4">
        <a href="compare?b=JohnRandall">JohnRandall</a>
    </td>
</tr>
<tr>
    <td style="padding:4px" width="100" height="1" align="left">
        Username:
    </td>
    <td style="padding:4px" height="1">
        <a href="compose?to=JohnRandall">JohnRandall</a>                                 
    </td>
    <td style="padding:4px" width="130" height="1">
        <a href="associates?uid=JohnRandall&as=Friend" style="color:#a6ffb5;">Add as friend</a>
    </td>
    <td width="300" style="padding:0px;margin:0;overflow:hidden;" rowspan="11" valign="top"><img src="//id.crimecdn.com/0gd74.jpg" width="300" style="display: block;max-height:2000px;"></td>
</tr>
<tr class="odd">
    <td style="padding:4px" align="left" height="1">
        Status:
    </td>
    <td style="padding:4px" height="1">
        <span style="color:#00ff00;" title="Online Now">&bull;</span> <span style="color:#00ff00;">Online</span>                               
    </td>
    <td style="padding:4px" height="1">
        <a href="associates?uid=JohnRandall&as=Blocked" style="color:#ffa6a6;">Add as enemy</a>
    </td>
</tr>
<tr>
    <td style="padding:4px" align="left" height="1">
        Crew:                                </td>
    <td height="1">
        <a href="/crew/25" style="border:0;display: block;"><img src="//id.crimecdn.com/o7yft.jpg" width="59" height="33" style="border:0;display: block;"></a>                                
    </td>
    <td style="padding:4px" height="1">
        <a href="compose?to=JohnRandall">Send message</a>
    </td>
</tr>
<tr class="odd">
    <td style="padding:4px" align="left" height="1">
        Wealth:
    </td>
    <td style="padding:4px" height="1">
        Dangerously Healthy <a href="#" onClick="confirm('This player has between $10,000,000 to $50,000,000.');return false;" style="color:#888;">(?)</a>                                
    </td>
    <td style="padding:4px" height="1">
        <a href="bank?to=JohnRandall">Send money</a>
    </td>
</tr>
<tr>
    <td style="padding:4px" align="left" height="1">
        Age:
    </td>
    <td style="padding:4px" height="1">
        28                                
    </td>
    <td style="padding:4px" height="1">
        <a href="escrow?to=JohnRandall">Send escrow</a>
    </td>
</tr>
<tr class="odd">
    <td style="padding:4px" align="left" height="1">
        Gender:
    </td>
    <td style="padding:4px" height="1">
        Male                                
    </td>
    <td style="padding:4px" height="1">
        <a href="kill.php?search=JohnRandall">Kill search</a>                                
    </td>
</tr>
<tr>
    <td style="padding:4px" align="left" height="1">
        Last Active:
    </td>
    <td style="padding:4px" height="1">
        Just now                                
    </td>
    <td style="padding:4px" height="1">
        <a href="compare?b=JohnRandall">Compare</a>                                
    </td>
</tr>
<tr class="odd">
    <td style="padding:4px" align="left" height="1">
        Date Joined:
    </td>
    <td style="padding:4px" height="1">
        2015-12-16                                
    </td>
    <td style="padding:4px" height="1">
        !--overlord2.php?id=lookup&prefill=JohnRandall-->
    </td>
</tr>
<tr>
    <td style="padding:4px" align="left" height="1">
        Messages:
    </td>
    <td style="padding:4px" height="1">
        2                                
    </td>
    <td style="padding:4px" height="1">
    </td>
</tr>
<tr>
    <td class="backdrop" style="padding: 4px;" colspan="3" height="1">
        <a href="edit" style="opacity:0.5;float:right;" class="hover"><img src="//caviar.dtmcdn.com/render/45865/12"> Edit my profile</a><p class="royal">Player quote</p>
    </td>
</tr>
<tr>
    <td colspan="3" valign="top" style="background-color:#2a2a2a !important;padding: 0 !important;">
        <div style="width:480px; overflow:hidden;">
            92                                    
        </div>
    </td>
</tr>

2 个答案:

答案 0 :(得分:2)

步骤1:目标数据结构:

您的数据结构存在两个问题:

  • 您忘记将名称放在引号之间。 John应为"John"Mary应为"Mary"。等

  • 您正在尝试使用[ "John", "Mary" ][ "Paul", "Peter" ]的对象,您应该使用数组。

因此,您正在寻找的数据结构是:

{
    31 : [ "John", "Mary" ],
    24 : [ "Paul", "Peter" ]
}

第2步:从HTML输入中获取数据:

我建议您对JavaScript代码进行一些小调整:

var source = [];

$('span.members a').each(function () {
    $.ajax({
        url: $(this).attr('href'),
        success: function (result) {
            source.push({
                name : $(result).find('tr td:contains("Username:")').next().text().trim(),
                age : $(result).find('tr td:contains("Age:")').next().text().trim()
            });
        }
    });
});

(另见this Fiddle

这将从HTML输入中获取数据并将其放入如下所示的数据结构中:

var source = [{
    name : "Paul",
    age : 24
}, {
    name : "Mary",
    age : 31
}, {
    name : "Peter",
    age : 24
}, {
    name : "John",
    age : 31
}];

第3步:转换为正确的数据结构:

获取所有数据后,您只需将数据从源数据结构转换为目标数据结构,这很简单:

var convert = function(source) {
    var output = {};
    for(var i = 0; i < source.length; i++) {
        if(output[source[i].age]) {
            output[source[i].age].push(source[i].name);
        } else {
            output[source[i].age] = [source[i].name];
        }
    }
    return output;
}

(另见this Fiddle

将拼图的各个部分放在一起:

您必须等待执行convert函数,直到所有Ajax调用完成。

例如,您可以执行类似......

的操作
if (source.length === numberOfMembers) {
    target = convert(source);
}

...紧跟source.push(...)声明。

因此,如果你把拼图的所有部分放在一起,你应该得到这样的东西:

var source = [];
var target;
var $members = $('span.members a');
var numberOfMembers = $members.size();

var convert = function(source) {
    var output = {};
    for(var i = 0; i < source.length; i++) {
        if(output[source[i].age]) {
            output[source[i].age].push(source[i].name);
        } else {
            output[source[i].age] = [source[i].name];
        }
    }
    return output;
}

$members.each(function () {
    $.ajax({
        url: $(this).attr('href'),
        success: function (result) {
            source.push({
                name : $(result).find('tr td:contains("Username:")').next().text().trim(),
                age : $(result).find('tr td:contains("Age:")').next().text().trim()
            });
            if (source.length === numberOfMembers) {
                target = convert(source);
            }
        }
    });
});

答案 1 :(得分:1)

这可以让你知道该怎么做:

abcArr = [["Paul", 24], ["Mary", 31], ["Peter",24],["John",31]];

var items = {}, base, key;
$.each(abcArr, function(index, val) {
    key = val[1];
    users = [];
    if (items[key]) {
        items[key].push(val[0]);
    }
    else {
        users.push(val[0])
      items[key] = users;
    }

});

var outputArr = [];
$.each(items, function(key, val) {
    outputArr.push([key, val]);
});

// outputArr contains the result
document.body.innerHTML = JSON.stringify(outputArr);

https://jsfiddle.net/rennomarcus/7Lvy0w1t/

我从这个主题得到了这个想法:jquery array group by