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

时间:2014-04-11 17:20:34

标签: javascript jquery arrays json each

好的,所以我只是一个JSON noob,只有基本的jQuery知识,而且我已经全神贯注地找到了一个解决方案并找不到解决方案。非常感谢任何帮助。

我需要:

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

2)显示" mbrname"

的前两个结果

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

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

以下是最终产品的截图: enter image description here

这是我的代码现在生成的内容: enter image description here

这是我的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"
           }
        ]
     }
  ]
 }
}

这是我的jquery仅仅是为了" mbrname"成功提取名称并将其附加到我的HTML的部分:

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

$(currentUser).append(mbrPart);

});

提前感谢您的帮助!

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

这样的事情应该有效。

var count = 0;
$.each (message.recipient, function (message, recipient) {


if(count<2){
var mbrPart = recipient.mbrname + ', ';
var currentUser = $('#' + newID + ' .name');
$(currentUser).append(mbrPart);
}
count++;
});

$(currentUser).append(" + " + count-2 + " Others");