2015-09-10 123 views
1

我有一個對象數組,其中每個對象都有一個「積分」屬性(示例數據如下)。我想展平積分榜數組並將其添加到父對象的末尾。Flatten array in array

[{ 
name: "Entry 1", 
value: 0, 
standings: [{ 
    week: 1, 
    team: 'MIN' 
    }, { 
    week: 2, 
    team: 'NE' 
    }, { 
    week: 3, 
    team: null 
    }] 
}, { 
name: "my Other Entry", 
value: 3, 
standings: [{ 
    week: 1, 
    team: 'BUF' 
    }, { 
    week: 2, 
    team: 'CIN' 
    }, { 
    week: 3, 
    team: 'TB' 
    }] 
}]; 

我如何獲得:

[{name: "Entry 1", value: 0, w1: 'MIN', w2: 'NE', w3: null}, 
{name: "my Other Entry", value: 3, w1: 'BUF', w2: 'CIN', w3: 'TB'}] 

我想變平的一些變化?

+1

你想以編程方式做到這一點在JavaScript?或者你正在尋找建議來命名你的平板JSON? –

回答

1

一個Array.prototype.reduce會做:

var data = [ 
 
     { 
 
      name: "Entry 1", 
 
      value: 0, 
 
      standings: [{ 
 
       week: 1, 
 
       team: 'MIN' 
 
      }, { 
 
       week: 2, 
 
       team: 'NE' 
 
      }, { 
 
       week: 3, 
 
       team: null 
 
      }] 
 
     }, { 
 
      name: "my Other Entry", 
 
      value: 3, 
 
      standings: [{ 
 
       week: 1, 
 
       team: 'BUF' 
 
      }, { 
 
       week: 2, 
 
       team: 'CIN' 
 
      }, { 
 
       week: 3, 
 
       team: 'TB' 
 
      }] 
 
     } 
 
    ], 
 
    data1 = data.reduce(function (r, a) { 
 
     r.push(a.standings.reduce(function (rr, b) { 
 
      rr['w' + b.week] = b.team; 
 
      return rr; 
 
     }, { 
 
      name: a.name, 
 
      value: a.value 
 
     })); 
 
     return r; 
 
    }, []); 
 
document.write('<pre>'+JSON.stringify(data1, 0, 4)+'</pre>');

1

我不認爲_.flatten將在這裏考慮您的數據結構有很大的幫助。

不使用庫,你可以只在您的數據環和手動轉換它:

function collapseStandings() { 
    var formattedData = []; 
    data.forEach(function(entry) { // data is your sample data. 
     var convertedObj = { 
      name: entry.name, 
      value: entry.value 
     }; 
     entry.standings.forEach(function(standing){ 
      convertedObj['w' + standing.week] = standing.team; 
     }); 

     formattedData.push(convertedObj);     
    }); 

    return formattedData; 
} 

完全fiddle