在保持键的顺序的同时反转对象值的顺序

时间:2017-12-20 14:44:43

标签: javascript javascript-objects

我有以下对象......

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

如何反转其键的十六进制值的顺序?这就是我想要实现的目标......

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

2 个答案:

答案 0 :(得分: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"}

答案 1 :(得分: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));