如何对 javascript 中的 key/value 个对象进行排序?

How to sort key/value objects in javascript?

How can I add a key/value pair to a JavaScript object? and Best way to store a key=>value array in JavaScript? 之后,我构建了我的 Key/Value 地图(对象)。

然后我像下面这样构建它 MyFunc returns 一个数组:

let MyMap = {}; // object
for(let i = 0; i < MyContainer.length; i++)
{
   // create the key (id of current element) and set its value as array of elements (result from MyFunc)
   await MyFunc(MyContainer[i]).then((response) => MyMap[MyContainer[i].id] = response); 
}

MyMap 看起来像这样:

MyMap = 
{
   1: [Object, Object, Object, …] // 13 elements
   2: [Object, Object, Object, …] // 7 elements
   3: [Object, Object, Object, …] // 4 elements
   4: [Object]
   5: [Object]
   6: [Object, Object, Object, …] // 5 elements
   7: [Object, Object, Object, …] // 9 elements
}

我想迭代我的映射(键),但从具有最小值(最小数组)的键开始。

因此,我想:

既然myMap是一个对象,那我就不能排序了。

我怎样才能做到这一点?

最终,您将无法使用对象,因为无法保证键的顺序

您可以:

  • 使用 Object.keys(obj) 获取对象的键作为 Array
  • 使用这些键构建结构对象的 Array,数组中的每个项目都是原始对象的 key/value 对。
  • 然后根据其中每个 item.value 的长度对 Array 个对象进行排序。本例中的 item.value 是原始对象的值,即 Arrays

const obj = {
  "1": [1, 2, 3],
  "2": [1],
  "3": [1, 2],
  "4": [1, 2, 3, 4]
};

// Transform object into a nested array
// Each array item contains the value of a key of your original object,
// which itself is an Array
const arr = Object.keys(obj).reduce((arr, key) => {
 arr.push({ key: key, value: obj[key] });
 
 return arr;
}, [])

// Sort the nested Array based on the length of each item
const sortedArr = arr.sort((a, b) => a.value.length - b.value.length);

console.log(sortedArr);

与上面相同但更紧凑,使用链接

const obj = {
  "1": [1, 2, 3],
  "2": [1],
  "3": [1, 2],
  "4": [1, 2, 3, 4]
};

const sortedArr = Object.keys(obj).reduce((arr, key) => {
  arr.push({ key: key, value: obj[key] });

  return arr;
}, [])
.sort((a, b) => a.value.length - b.value.length)

console.log(sortedArr);