2017-10-15 2 views
-2

Comment convertir un objet javascript en un tableau d'objets? Les éléments de tableau doivent être commandés par la propriété index dans l'objet d'origine:Convertir un objet javascript en tableau avec une commande spécifique

Entrée:

var o = { 
    "0gfbpa1508024708952": { 
    title: "hi daughter", 
    index: 3 
    }, 
    "b8tl5k1508024741100": { 
    title: "hi dad", 
    index: 0 
    }, 
    "cxr9x1508024697320": { 
    title: "hi son", 
    index: 2 
    }, 
    "qua2802469732": { 
    title: "hi cousin", 
    index: 9007199254740991 
    }, 
    "tck80i1508024731561": { 
    title: "hi mom", 
    index: 1 
    } 
}; 

Sortie:

[ 
    {id: "b8tl5k1508024741100", title: "hi dad"},  // array index 0 
    {id: "tck80i1508024731561", title: "hi mom"},  // array index 1 
    {id: "cxr9x1508024697320", title: "hi son"},   // array index 2 
    {id: "0gfbpa1508024708952", title: "hi daughter"}, // array index 3 
    {id: "qua2802469732", title: "hi cousin"}   // array index 4 
] 

This question seulement aide à la commande/tri des tableau. Il n'explique pas comment (1) transformer la clé de l'objet en propriété de l'objet tableau id et (2) comment supprimer la clé index du tableau. Il y a une transformation qui se passe ici, pas seulement une commande/un tri basé sur des clés d'objets.

+4

double possible de [Conversion d'un littéral d'objet à un tableau trié] (https://stackoverflow.com/questions/13694883/converting-an-object-literal-to-a-sorted-array) –

Répondre

0
let o = { 
    "0gfbpa1508024708952": { 
    title: "hi daughter", 
    index: 3 
    }, 
    "b8tl5k1508024741100": { 
    title: "hi dad", 
    index: 0 
    }, 
    "cxr9x1508024697320": { 
    title: "hi son", 
    index: 2 
    }, 
    "qua2802469732": { 
    title: "hi cousin", 
    index: 9007199254740991 
    }, 
    "tck80i1508024731561": { 
    title: "hi mom", 
    index: 1 
    } 
}, 
arr = []; 


for (let k in o) { 
    let tmp = o[k]; 
    tmp.id = k; 
    arr.push(tmp); 
} 
arr.sort(function(a,b) { return a.index - b.index; }); 

for (let k in arr) 
    delete arr[k].index;