循环通过JSON数组,显示两个,然后显示Count

Nic*_*Coy 1 javascript arrays each jquery json

好吧,所以我是一个JSON noob,只有基本的jQuery知识,我一直在找一个解决方案,找不到一个.任何帮助是极大的赞赏.

我需要:

1)循环通过JSON数组(工作)

2)显示"mbrname"的前两个结果

3)然后显示其余结果的计数.

我成功循环并显示所有mbrname结果.但不知何故,我只需显示前两个,如果有更多显示"+#others"

以下是最终产品应如下所示的屏幕截图: 在此输入图像描述

这是我的代码现在生成的内容: 在此输入图像描述

这是我的JSON:

{
 "messages":{
  "message":[
     {
        "date-time":"June 2, 2013 12:22 pm",
        "subject":"This is the message subject",
        "msg-string":"001",
        "newmsg":"true",
        "attach":"shop-cart",
        "recipient":[
           {
              "mbrname":"D. Craig",
              "mbr-href":"#craig"
           },
           {
              "mbrname":"N. McCoy",
              "mbr-href":"#mccoy"
           },
           {
              "mbrname":"J. Smith",
              "mbr-href":"#smith"
           },
           {
              "mbrname":"B. Wardlaw",
              "mbr-href":"#wardlaw"
           }
        ]
     },
     {
        "date-time":"May 23, 2013 12:22 pm",
        "subject":"This is a great subject",
        "attach":"none",
        "msg-string":"002",
        "newmsg":"true",
        "recipient":[
           {
              "mbrname":"D. Craig",
              "mbr-href":"#craig"
           },
           {
              "mbrname":"N. McCoy",
              "mbr-href":"#mccoy"
           }
        ]
     },
     {
        "date-time":"May 11, 2013 12:22 pm",
        "subject":"Interested in your tomatoes",
        "attach":"shop-cart",
        "msg-string":"003",
        "newmsg":"false",
        "recipient":[
           {
              "mbrname":"J. Smith",
              "mbr-href":"#smith"
           }
        ]
     }
  ]
 }
}
Run Code Online (Sandbox Code Playgroud)

这是我的jquery只是为了"mbrname"部分,它成功地提取名称并将它们附加到我的HTML:

$.each (message.recipient, function (message, recipient) {
var mbrPart = recipient.mbrname + ', ';
var currentUser = $('#' + newID + ' .name');

$(currentUser).append(mbrPart);

});
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助!

Jas*_*n P 6

我会保持简单,不需要做任何循环:

var recipientString = message.recipient[0].mbrname;
var count = message.recipient.length;

if (count > 1)
    recipientString += ', ' + message.recipient[1].mbrname;

if (count > 2)
    recipientString += ' + ' + (count - 2) + ' others';

$('#' + newID + ' .name').append(recipientString);
Run Code Online (Sandbox Code Playgroud)