如何从对象javascript数组创建特定对象? [英] How can I create a specific object from an array of objects javascript?
本文介绍了如何从对象javascript数组创建特定对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我没有灵感,可能很简单,但我要做的只是idk。
I'm out of inspiration and probably is very simple what I have to do but idk.
让我们说我们有这个数组:
Let's say we have this array :
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: ....
}
]
所以我从问题数组中需要的是另一个这样的数组:
So what I need from questions array is another array like this:
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数组创建特定对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文