2016-03-24 21 views
1

İlham kaynağım var ve muhtemelen yapmam gereken şey çok basit ama idk.Javascript nesnesinin bir dizisinden belirli bir nesneyi nasıl oluşturabilirim?

Şimdi bu dizi var diyelim:

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

Ve böylece .. Temelde ben oluşturmak istiyorum:

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: .... 
    } 
] 

Yani sorular diziden ne gerek bu gibi başka bir dizidir skor tablosu bir cevap tablosundan çıktı. Nesneleri tekrarlamadan çıkarmayı başardım. Bu yardımın bana yardımcı olup olmadığından emin değilim: https://plnkr.co/edit/rXRrPc1MrSs181GBv8tf?p=preview

+0

olası çift [nesneleri JavaScript dizi GroupBy için en etkili yöntem nedir?] (http://stackoverflow.com/questions/14446511/what-is-the -en-verimli-yöntem-için-grup-on-a-javascript-nesneleri-dizi) –

+1

Evet ama anladığım kadarıyla, anlamadığım pek çok şey var. Ancak, gelecekte size yardımcı olabilecek bağlantı için teşekkürler. – Shaker

cevap

2

Gruplandırılmış verilerle yeni bir dizi oluşturabilir ve oluşturabilirsiniz. bir

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

+0

Bu tam olarak ihtiyacım olan şey. Çok teşekkür ederim ! – Shaker

İlgili konular