简体   繁体   English

如何根据键对 object 进行排序

[英]How to sort an object based on the key

Suppose i have an object obj1= {key1:[1,2,3],key2:[333,11],key3:[9938,33,0,39,2]} How to sort this by length of value array.假设我有一个 object obj1= {key1:[1,2,3],key2:[333,11],key3:[9938,33,0,39,2]}如何按值数组的长度对其进行排序。 I tried using Lodash method but that didnt worked.我尝试使用 Lodash 方法,但没有奏效。 Required output需要 output

obj1= {key3:[9938,33,0,39,2],key1:[1,2,3],key2:[333,11]}

First a disclaimer: JavaScript objects are typically considered to be unordered key/value pairs.首先声明:JavaScript 对象通常被认为是无序的键/值对。 While recent versions of the ECMAScript specification do stipulate how object properties are ordered, the rules are complex, and it remains good advice to not rely on object order unless you know what you're doing.虽然最新版本的 ECMAScript 规范确实规定了 object 属性的顺序,但规则很复杂,除非您知道自己在做什么,否则不要依赖 object 顺序仍然是一个很好的建议。

That being said, you can use Object.entries() and Object.fromEntries() to get your desired result:话虽如此,您可以使用Object.entries()Object.fromEntries()来获得您想要的结果:

 const o = { key1: [1,2,3], key2: [333,11], key3: [9938,33,0,39,2] }; const r = Object.fromEntries( Object.entries(o).sort(([k1, v1], [k2, v2]) => v2.length - v1.length) ); console.log(r);

test it测试一下

 let obj2={} let obj1= {key3:[9938,33,0,39,2],key1:[1,2,3],key2:[333,11]} Object.keys(obj1).sort((a,b)=>{ if (obj1[a].length>obj1[b].length) { return -1 } if (obj1[a].length<obj1[b].length) { return 1 } return 0 }).map(x=>{ obj2[x]=obj1[x] }) console.log(obj2);

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

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