2017-12-20 7 views
0

Ich habe folgendes Objekt ...unter Beibehaltung der Reihenfolge der Tasten

{0: "#000000", 1: "#FFFFFF", 0.292: "#ff0000", 0.7: "#3498db"} 

Wie kann in umgekehrter Reihenfolge der Hex-Werte jeweils auf ihre Schlüssel? Dies ist, was ich erreichen will ...

{0: "#FFFFFF", 0.292: "#3498db", 0.7: "#ff0000", 1: "#000000"} 
+3

Die Reihenfolge der Tasten ist nicht garantiert und offen gesagt, sollte es keine Rolle. –

+0

Was sind die Kriterien für die Neuanordnung der Immobilienwerte? – Pointy

+0

Bitte lesen Sie die Frage besser. –

Antwort

0
function reverseValues(original) { 
    // put into a combination array 
    var combined = []; 
    for (var key in original) { 
    // note: keys are always strings! So use +key to convert to a number for sorting 
    combined.push({key: +key, val: original[key]}); 
    } 

    // sort it by the key value 
    combined.sort((a, b) => a.key - b.key); 

    // Create the result 
    var result = {}; 
    var combinedMax = combined.length - 1; 
    combined.forEach((kv, i) => result[kv.key] = combined[combinedMax - i].val); 
    return result; 
} 

var testVal = {0: "#000000", 1: "#FFFFFF", 0.292: "#ff0000", 0.7: "#3498db"}; 
console.dir(reverseValues(testVal)); 
0
function updateKVs(data) { 
    // Grab the object properties and sort them 
    const keys = Object.keys(data).sort(); 

    // grab the values 
    const valuesRaw = Object.values(data); 

    // convert them to integers and sort. 
    // NOTE: you need to drop the initial `#` or it will return NaN 
    const valuesSortedInts = valuesRaw.map((n) => parseInt(n.substr(1), 16)).sort() 

    // convert back to hex. Include padding to make the value match inital. 
    const valuesSortedHex = valuesSortedInts.map(
     (n) => n.toString(16).padStart(6, '0') 
    ); 

    // Iterate through the keys, re-assigning them. 
    keys.forEach((kv, i) => data[kv] = '#' + valuesSortedHex[i]); 
    return data; 
} 

updateKVs({0: "#000000", 1: "#FFFFFF", 0.292: "#ff0000", 0.7: "#3498db"}) 
> {0: "#000000", 1: "#3498db", 0.292: "#ff0000", 0.7: "#ffffff"} 
Verwandte Themen