我有一个对象数组如下:
[ { user: 'Abc', badge: [ 6 ] },
{ user: 'PQR', badge: [ 7 ] },
{ user: 'PQR', badge: [ 1 ] },
{ user: 'PQR', badge: [ 2 ] },
{ user: 'XYZ', badge: [ -5 ] } ]
我使用以下javascript代码创建了此对象:
for (var j = 0; j < aR.length; j++)
{
if (typeof aR[j] != 'undefined' && aR[j] != null)
{
recievedUser =aR[j].get("receiver").id;
badge = aR[j].get("rBTypes");
if(recievedUser!= undefined && badge != undefined )
result.push({'user': recievedUser, 'badge': badge});
}
}
现在我想将这个数组合并为:
[ { user: 'Abc', badge: [ 6 ] },
{ user: 'PQR', badge: [ 7 ,1,2] },
{ user: 'XYZ', badge: [ -5 ] } ]
我怎么能这样做?
我还想找到徽章最多的用户?
答案 0 :(得分:0)
您可以将Array#forEach()
与thisArgs
一起用于临时对象作为对分组元素的引用。
var data = [{ user: 'Abc', badge: [6] }, { user: 'PQR', badge: [7] }, { user: 'PQR', badge: [1] }, { user: 'PQR', badge: [2] }, { user: 'XYZ', badge: [-5] }],
grouped = [],
mostUser = [];
data.forEach(function (a, i) {
if (!this[a.user]) {
this[a.user] = { user: a.user, badge: [] };
grouped.push(this[a.user]);
}
this[a.user].badge = this[a.user].badge.concat(a.badge);
if (!i || this[a.user].badge.length > this[mostUser[0]].badge.length) {
mostUser = [a.user];
return;
}
if (a.user !== mostUser[0] && this[a.user].badge.length === this[mostUser[0]].badge.length) {
mostUser.push(a.user);
}
}, Object.create(null));
document.write('<pre>' + JSON.stringify(mostUser, 0, 4) + '</pre>');
document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');
&#13;
答案 1 :(得分:0)
首先,如果你想完成你问题评论中提到的deceze的微不足道的重组结果。只需将代码中的push语句更改为:result.push({recievedUser: badge});
现在计算哪个用户拥有最多的徽章:
// Add these variables here
var most_badges = 0;
var user_with_most;
for (var j = 0; j < attendeeReflections.length; j++)
{
if (typeof attendeeReflections[j] != 'undefined' && attendeeReflections[j] != null)
{
recievedUser =attendeeReflections[j].get("receiver").id;
badge = attendeeReflections[j].get("requestedBehaviorTypes");
// Add this check here
if(badge.length > most_badges) {
most_badges = badge.length;
user_with_most = recievedUser;
}
// Now you have your results
if(recievedUser!= undefined && badge != undefined )
result.push({'user': recievedUser, 'badge': badge});
}
}
现在,您拥有user_with_most
变量中存储的徽章最多的用户以及用户存储在most_badges
变量中的徽章数量。
答案 2 :(得分:0)
你可以修改你的功能,在推入新项目之前检查返回的结果,
或者您已经拥有的输出可以使用Array.reduce来组织数组,
这是一个使用reduce()的解决方案:
var a = [ { user: 'Abc', badge: [ 6 ] },
{ user: 'PQR', badge: [ 7 ] },
{ user: 'PQR', badge: [ 1 ] },
{ user: 'PQR', badge: [ 2 ] },
{ user: 'XYZ', badge: [ -5 ] } ]
var r= a.reduce((ac,x) => {
(ac.some(z => {
if(z.user === x.user)
z.badge.push(x.badge[0]);
return (z.user === x.user);}))
|| (ac.push(x));
return ac;
},[])
console.log(r)