简体   繁体   中英

How to sort object of objects by sub-object value?

I have an object like this:

let objectExample = {
    key1: { prop1: '123', prop2: 'def' },
    key2: { prop1: '456', prop2: 'ghi' },
    key3: { prop1: '789', prop2: 'abc' }
};

And need it to be like this after sort by prop2 's value.

let objectSorted = {
    key3: { prop1: '789', prop2: 'abc' },
    key1: { prop1: '123', prop2: 'def' },
    key2: { prop1: '456', prop2: 'ghi' }
};

I've seen some examples here, but they look too unreadable now and scare me as a beginner :D Also the question I've seen have been asked, like, 6 years ago.

There is no way to sort object properties, they has no index order. If you want to keep specific order of elements, you have to use array, not object. And here is an example, how to sort an array alphabetically:

 let arrExample = [ { prop1: '123', prop2: 'def' }, { prop1: '456', prop2: 'ghi' }, { prop1: '789', prop2: 'abc' } ]; arrExample.sort(function(a, b){ if(a.prop2 < b.prop2) return -1; if(a.prop2 > b.prop2) return 1; return 0; }) console.log(arrExample); 

Sorry don't have a laptop now. But the code below should help.

let objectExample = { key1: { prop1: '123', prop2: 'def' }, key2: { prop1: '456', prop2: 'ghi' }, key3: { prop1: '789', prop2: 'abc' } };

let objectSorted = {};
 Object.keys(objectExample).sort((key1,key2) => {
    return objectExample[key1].prop2.localeCompare(objectExample[key2].prop2);
}).forEach((element) => {
    objectSorted[element] = objectExample[element];
});

console.log(JSON.stringify(objectSorted));

I would not rely on object key order. The most appropriate is to use arrays for sorting purposes, as they are explicitly ordered. For object keys you should probably treat them as ordered... I would think of them as a set.

Said this, the object keys have in the end an order, that is insertion order, as it is shown when you iterate them with for..in or by using Object.keys. You can not easily modify that order of a key after it is set, the only option is to delete it, and then set it again, that would "move" it into the last position. But again, even if it is possible to do this kind of stuff, I would not recommend it at all... even less to try to sort them. Use an array, then use the sort method provided by the array.

Property order is predictable in JavaScript objects since ES2015

You may do other stuff than Object sorting. For example output an ordered list.
Then this is an cross-browser IE9+ solution .
And there is No need of any intermediate Array !

1.  var objectSorted = {}, x, y
2.  var size = Object.keys(objectExample).length; //IE9+
3.  while (size--) {
4.    y = null
5.    for (var key in objectExample) {
6.      var z = objectExample[key].prop2;
7.      if (!objectExample.hasOwnProperty(key)) continue;
8.      if (!y || z < y) {
9.        x = key
10.       y = z;
11.     }
12.   }
13.
14.   objectSorted[x] = objectExample[x];
15.
16.   delete objectExample[x]
17. }

Some description

2 Get length of object .
4 y will be the next lowest found string. Forget the deleted one.
5 Iterate an object with a for-in .
6 Let z be the property to be sorted on.
7 Skip eventual prototypes as told here .
8 if a lower string than the lowest is found then ...
9 Remember the key to the lowest found string.
10 And remember the lowest found string.
14 Push the new object with the found value.
16 Delete the key and its value from the old object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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