gpt4 book ai didi

javascript - 遍历 JSON 数组,显示两个然后计数

转载 作者:行者123 更新时间:2023-11-30 07:38:50 25 4
gpt4 key购买 nike

好吧,我是一个 JSON 菜鸟,只有基本的 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"
}
]
}
]
}
}

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

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

$(currentUser).append(mbrPart);

});

在此先感谢您的帮助!

最佳答案

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

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);

关于javascript - 遍历 JSON 数组,显示两个然后计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23018832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com