简体   繁体   English

如何在JS中仅对对象的值排序?

[英]How to sort only the values of an object in JS?

I have a JS object defined as this {0: 3, 2: 2, 4: 1} , and I want to sort only the values, and leave the keys in tact. 我有一个JS对象定义为{0: 3, 2: 2, 4: 1} ,我只希望对值进行排序,而键则保持原样。 What I mean is that after the object is sorted, the end result should be {0: 1, 2: 2, 4: 3} , so only the values change their places and not the keys. 我的意思是,对对象进行排序后,最终结果应为{0: 1, 2: 2, 4: 3} ,因此只有值会更改其位置,而不是键。

I have the following code segment: 我有以下代码段:

let list = {0: 3, 2: 2, 4: 1};
Object.keys(list)
      .sort((a, b) => list[a]-list[b])
      .reduce((obj, key) => ({
          ...obj, 
          [key]: list[key]
      }), {});

But, it doesn't seem to work. 但是,它似乎不起作用。 In fact, it doesn't seem to sort it at all. 实际上,它似乎根本没有对它进行排序。 Any ideas how to achieve what I want in JS? 有什么想法如何实现我想要的JS吗?

You could sort the values, the keys stays in ascending order, because object's keys who are integers are sorted by default. 您可以对值进行排序,键保持升序,因为默认情况下,对象的整数键是排序的。 Later assign the sorted values to the keys. 稍后将排序后的值分配给键。

 var list = { 0: 3, 2: 2, 4: 1 }, values = Object.values(list).sort((a, b) => a - b), result = Object.assign(...Object.keys(list).map((k, i) => ({ [k]: values[i] }))); console.log(result); 

There are more elegant solutions involving 3rd party libraries (need zip , partition , etc.), but this should get you there: 还有涉及第三方库(需要zippartition等)的更优雅的解决方案,但这应该可以帮助您:

let foo = {0: 3, 2: 2, 4: 1};

// here we'll just sort the keys and values independently and then
// recombine them
let keys = Object.keys(foo).sort((a, b) => a - b);
let vals = Object.values(foo).sort((a, b) => a - b);
let result = keys.reduce((acc, k, i) => (acc[k] = vals[i], acc), {});

Another solution more 另一个解决方案

let list = {
   0: 3,
   2: 2,
   4: 1
}

let values=Object.values(list).sort()

Object.keys(list)
  .sort()
  .reduce((obj, key, i) => ({
      ...obj,
        [key]: values[i]
  }), {});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM