gpt4 book ai didi

javascript - 如何从对象数组 javascript 创建特定对象?

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

我没有灵感了,我要做的可能很简单,但我不知道。

假设我们有这个数组:

var answers = [
{
name: 'Name 1',
score: 5,
correct_ans: 'y'
challenge: ....
},
{
name: 'Name 2',
score: 10,
correct_ans: 'n',
challenge: ....
},
{
name: 'Name 1',
score: 12,
correct_ans: 'y',
challenge: ....
},
{
name: 'Name 2',
score: 8,
correct_ans: 'y',
challenge: ....
}
]

所以我从问题数组中需要的是另一个像这样的数组:

var array = [
{
name: 'Name1',
overall_score: --total score-- if the correct_ans is y
score: [
{
score: 5,
challenge: ....
}
]
}
]

等等..基本上我想从答案表中创建一个排行榜。我设法提取了对象而不重复它们我不确定这是否对我有帮助:https://plnkr.co/edit/rXRrPc1MrSs181GBv8tf?p=preview

最佳答案

您可以使用分组数据迭代并构建一个新数组。

var questions = [{ team_name: 'Team A', points: 0, correct_ans: 'n' }, { team_name: 'Team B', points: 10, correct_ans: 'y' }, { team_name: 'Team A', points: 15, correct_ans: 'y' }, { team_name: 'Team B', points: 15, correct_ans: 'y' }, { team_name: 'Team A', points: 20, correct_ans: 'y' }, { team_name: 'Team B', points: 20, correct_ans: 'y' }],
array = function (array) {
var r = [];
array.forEach(function (a) {
if (a.correct_ans !== 'y') {
return;
}
if (!this[a.team_name]) {
this[a.team_name] = { team_name: a.team_name, overall_score: 0, score: [] };
r.push(this[a.team_name]);
}
this[a.team_name].overall_score += a.points;
this[a.team_name].score.push({ points: a.points, correct_ans: a.correct_ans });
}, {});
return r;
}(questions);

document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

关于javascript - 如何从对象数组 javascript 创建特定对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36196298/

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