2017-09-25 74 views
0

我有以下數據結構:轉換數據

const data = [ 
    { 
    name: 'ABC', 
    salesData: [ 
     { 
     timestamp: '2017-09-01', 
     value: 10 
     }, 
     { 
     timestamp: '2017-09-02', 
     value: 2 
     } 
    ] 
    }, 
    { 
    name: 'DEF', 
    salesData: [ 
     { 
     timestamp: '2017-09-01', 
     value: 8 
     }, 
     { 
     timestamp: '2017-09-02', 
     value: 3 
     } 
    ] 
    } 
]; 

我想這個轉換爲:

[ 
    { 
    name: 'ABC', 
    '2017-09-01': 10, 
    '2017-09-02': 2 
    }, 
    { 
    name: 'CDE', 
    '2017-09-01': 8, 
    '2017-09-02': 3 
    } 
] 

我試圖使用下劃線的鏈和地圖,我越來越困惑。到目前爲止,我有以下的,不知道怎麼辦我寫的convertedSalesData爲每個需要變換:

_.map(data, function(item) { 
    let name = item.name; 
    let salesData = item.salesData; 
    let convertedSalesData = ? 
}) 
+0

是否強制使用underscoreJS? –

+0

使用[]括號代替。將日期用作鍵。 –

+0

@HarshPatel:不是,我也很喜歡純JavaScript。 –

回答

2

隨着ES6您可以使用傳播語法...得到這個結果。

const data = [{"name":"ABC","salesData":[{"timestamp":"2017-09-01","value":10},{"timestamp":"2017-09-02","value":2}]},{"name":"DEF","salesData":[{"timestamp":"2017-09-01","value":8},{"timestamp":"2017-09-02","value":3}]}] 
 

 

 
var result = data.map(function({name, salesData}) { 
 
    return {name, ...Object.assign({}, ...salesData.map(({timestamp, value}) => ({[timestamp]: value})))} 
 
}) 
 
console.log(result)

+0

看起來很完美,使用ES6來達到這個效果真棒。感謝分享這個技巧。 –

+0

不客氣。 –

2

const data = [{ 
 
    name: 'ABC', 
 
    salesData: [{ 
 
     timestamp: '2017-09-01', 
 
     value: 10 
 
     }, 
 
     { 
 
     timestamp: '2017-09-02', 
 
     value: 2 
 
     } 
 
    ] 
 
    }, 
 
    { 
 
    name: 'DEF', 
 
    salesData: [{ 
 
     timestamp: '2017-09-01', 
 
     value: 8 
 
     }, 
 
     { 
 
     timestamp: '2017-09-02', 
 
     value: 3 
 
     } 
 
    ] 
 
    } 
 
]; 
 

 
var res = data.map(function(a) { 
 
    var obj = { 
 
    name: a.name 
 
    }; 
 
    a.salesData.forEach(function(x) { 
 
    obj[x.timestamp] = x.value; 
 
    }) 
 
    return obj; 
 
}) 
 

 
console.log(res);

2

到@Nenad Vracar區類似。我傾向於使用'減少':

data.map(({ name, salesData }) => ({ 
    name, 
    ...salesData.reduce(
    (record, { timestamp, value }) => { 
     record[timestamp] = value 
     return record 
    }, 
    Object.create(null) 
) 
})) 
+0

我想我們可以直接使用'{}'而不是'Object.create(null)'。這是同樣的東西 – RamaKrishna

+0

我建議使用Object.create(null)當你只需要一個普通的對象來存儲k/v對。這種通過這種方式創建的'{}'不會繼承Object.prototype的內容。當你在事物上循環時,你會很高興不寫'hasOwnProperty'。 – Zheeeng