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

问题描述 投票:0回答:2

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

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

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

{0: "#FFFFFF", 0.292: "#3498db", 0.7: "#ff0000", 1: "#000000"}
javascript javascript-objects
2个回答
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"}
© www.soinside.com 2019 - 2024. All rights reserved.