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

时间:2016-03-24 08:55:37

标签: javascript arrays html5 oop

我没有灵感,可能非常简单,我只能这样做,但是很高兴。

假设我们有这个数组:

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

1 个答案:

答案 0 :(得分:2)

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



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>');
&#13;
&#13;
&#13;

相关问题