2017-10-05 43 views
0

我需要梳理我的數組,他是這樣的:排序數據「ABR/2017年」

x = { 
    'Abr/2017': [ { id: 1 } ], 
    'Fev/2018': [ { id: 1 } ], 
    'Jul/2017': [ { id: 1 } ], 
    'Abr/2018': [ { id: 1 } ], 
    'Fev/2017': [ { id: 1 } ], 
    'Jul/2018': [ { id: 1 } ], 
    'Dez/2019': [ { id: 1 } ] 
} 

,我需要他成爲第一個在一年,然後進行排序在幾個月

+0

對象沒有秩序。 –

+0

'x'不是一個數組,它是一個對象。對象鍵沒有順序。 –

回答

0

因爲您的數據被表示爲對象,您必須將其轉換爲數組作爲第一步。然後你可以排序。之後你可以將結果數組映射到任何你想要的。

重要的是,如果你想保持這些數據以某種順序,那麼你必須使用陣列結構

let x = { 
 
    'Abr/2017': [ { id: 1 } ], 
 
    'Fev/2018': [ { id: 1 } ], 
 
    'Jul/2017': [ { id: 1 } ], 
 
    'Abr/2018': [ { id: 1 } ], 
 
    'Fev/2017': [ { id: 1 } ], 
 
    'Jul/2018': [ { id: 1 } ], 
 
    'Dez/2019': [ { id: 1 } ] 
 
} 
 
// this function transform your object to array representation 
 
// where your actual key (e.g. Fev/2017) is stored in helper 
 
// property called key 
 
function toArray(obj) { 
 
    return Object.keys(obj).reduce((arr, key) => { 
 
    arr.push({ key, data: obj[key] }) 
 
    return arr 
 
    }, []) 
 
} 
 

 
function byYearAndMonth() { 
 
    // month definition - help with sorting 
 
    let monthOrder = { 
 
    'Jan': 1, 
 
    'Fev': 2, 
 
    'Mar': 3, 
 
    'Abr': 4, 
 
    'Mai': 5, 
 
    'Jun': 6, 
 
    'Jul': 7, 
 
    'Ago': 8, 
 
    'Set': 9, 
 
    'Out': 10, 
 
    'Nov': 11, 
 
    'Dez': 12 
 
    } 
 
    let mapDate = function([month, year]) { 
 
    return [monthOrder[month], Number(year)] 
 
    } 
 

 
    // actual sorting function 
 
    return function(a, b) { 
 
    const [aMonth, aYear] = mapDate(a.key.split('/')) 
 
    const [bMonth, bYear] = mapDate(b.key.split('/')) 
 
    if(aYear < bYear) { 
 
     return -1 
 
    } 
 
    if(aYear > bYear) { 
 
     return 1 
 
    } 
 
    if(aMonth < bMonth) { 
 
     return -1 
 
    } 
 
    if(aMonth > bMonth) { 
 
     return 1 
 
    } 
 
    return 0 
 
    } 
 
} 
 

 
// lets try how it works 
 
let xArray = toArray(x) 
 
xArray.sort(byYearAndMonth()); 
 
var result = xArray.map(x => x) 
 
// with map (or reduce) you can transform it to whatever you want 
 
// I'm just returning exactly the same object 
 
console.log(result)